LeetCode 202:Happy Number
2015-12-13 00:45
423 查看
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
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
//利用set记录每次得到的平方和,当出现非1的重复平方和时,返回False,否则,返回True class Solution { public: bool isHappy(int n) { set<int> set1; if (n <= 0) return false; if (n == 1) return true; int sum = 0; int p = 0; while (n!=1 ){ while (n){ p = n % 10; n = n / 10; sum = sum + p*p; } if (set1.find(sum)!=set1.end()) return false; n = sum; sum = 0; set1.insert(n); } return n == 1; } };
相关文章推荐
- iOS键盘的关闭
- Android Development Notes-2
- android-Accessible
- android手势滑动处理
- iOS--tableView中的多余的线的去除方法
- Android相关问题的好文章整理——温故而知新,可以为师矣
- Android全面的屏幕相关工具
- android volley缓存设计分析
- Android SharedPreferences使用
- nineoldandroids的使用
- Cocos2d-x 之 自己生成API文档
- Json数据格式介绍、使用Android自带类库完成Json生成与解析
- iOS 单例模式全面解析
- Activity管理工具类AppManager
- Android 属性动画三剑客
- SpringMVC----RequestMapping映射请求
- Android SHA1与Package获取方式
- iOS传感器开发——加速度传感器,螺旋仪传感器,磁力传感器的应用
- 如何保证Android与服务器的DES加密保持一致
- iOS 中KVC、KVO、NSNotification、delegate 总结及区别