Happy Number
2015-11-28 10:37
357 查看
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
class Solution { public: bool isHappy(int n) { if(n<=0){ return false; } unordered_set<int> uset; int squareSum = 0; while(squareSum!=1){ squareSum = 0; while(n){ squareSum += (n%10)*(n%10); n /= 10; } n = squareSum ; if(uset.find(n)!=uset.end()){ return false; } uset.insert(n); } return true; } };
相关文章推荐
- 【神器】insert_dylib 给 MacOSX APP 添加导入表注入--你懂的~~
- Android控件之AlertDialog-自定义对话框
- android log 学习
- iOS 视图控制器(ViewController)中的代码规范
- ios 常见问题总结
- Android控件之AlertDialog-单选、多选信息列表弹出框
- IOS安全学习资料汇总
- 126 You executed the following commands in a database session: SQL> SELECT object_name, original_nam
- android:ToolBar详解(手把手教程)
- cocos2d-x-3.x-026 移植cocos的jnihelper及用法说明
- Android编程实现二维码的生成与解析
- LibAhead for iOS - 在未越狱设备上修改三方APP的功能
- Objective-C的m文件中定义变量
- Android NDK开发之JNI调用Java对象
- android移动view之后刷新布局导致移动后的view归回原位置2
- iOS开发:在Swift中调用oc库
- Android开发优化之——使用软引用和弱引用
- android移动view之后刷新布局导致移动后的view归回原位置1
- android项目MD5加密
- 微博app中常用正则表达式