[LeetCode202]Happy Number判断一个数是不是happy number
2015-12-19 20:52
337 查看
题目:
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
中文(把一个正整数各位平方后相加,然后把得到的结果各位平方相加....依次进行下去,如果能得到结果1则是happy number,否则不是)
思路:同计算循环小数一样,把每次计算的结果保存到一个List<int>里,如果出现循环,则返回false即可
代码:
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
中文(把一个正整数各位平方后相加,然后把得到的结果各位平方相加....依次进行下去,如果能得到结果1则是happy number,否则不是)
思路:同计算循环小数一样,把每次计算的结果保存到一个List<int>里,如果出现循环,则返回false即可
代码:
public class Solution { public bool IsHappy(int n) { int sum = n; if(n <= 0) return false; List<int> appearedNum = new List<int>(); while(true) { if(appearedNum.Contains(sum)) return false; else appearedNum.Add(sum); sum = GetNext(sum); if(sum == 1) return true; } return true; } public int GetNext(int num) { int sum = 0; while(num != 0) { sum += (int)Math.Pow(num % 10, 2); num /= 10; } return sum; } }
相关文章推荐
- iOS开发流程总结
- iOS性能优化:Instruments使用实战
- Android 单元测试
- cocos2d+sublime开发lua项目
- iOS App添加Spotlight搜索(附Swift Demo)
- ios workspace使用依赖工程 —笔记
- App市场的“繁荣”背后 隐藏令人唏嘘的真相
- iOS项目集成百度地图方法以及问题解决
- 微信分享及授权登录
- Android抓包方法(一)
- Android studio Cannot reload AVD list问题解决
- 【Android】Android Studio 进行代码混淆,打包release APK
- swift学习日记(十) 类型转换 类型嵌套
- processing-MySQL learning2-append()
- 微信公众平台开发(110) 微信连Wi-Fi
- IOS多线程系统学习之线程同步与线程通信
- android动画 属性动画详解
- Android开发中使用WebView视图显示网页的注意点
- Android Service完全解析,关于服务你所需知道的一切
- 关于序列化对象.Serializable Object总结.