202. Happy Number
2016-07-03 10:44
465 查看
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
Credits:
Special thanks to
@mithmatt and
@ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
注意c++中没有乘方运算符。
不要把异或搞混了。
代码
class Solution {
public:
bool isHappy(int n) {
set<int> s1;
while(n!=1)
{
int temp=0;
while(n>=10)
{
temp+=((n%10)*(n%10));
n=n/10;
}
temp+=(n*n);
if(s1.find(temp)!=s1.end())
{
return false;
}
s1.insert(temp);
n=temp;
}
return true;
}
};
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
Credits:
Special thanks to
@mithmatt and
@ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
注意c++中没有乘方运算符。
不要把异或搞混了。
代码
class Solution {
public:
bool isHappy(int n) {
set<int> s1;
while(n!=1)
{
int temp=0;
while(n>=10)
{
temp+=((n%10)*(n%10));
n=n/10;
}
temp+=(n*n);
if(s1.find(temp)!=s1.end())
{
return false;
}
s1.insert(temp);
n=temp;
}
return true;
}
};
相关文章推荐
- Handler消息机制原理
- Android开发中List的remove()方法
- Android基础知识总结
- Android 实现类似IOS App唤醒的代理方法
- java基础之一---java Application初步
- Android客户端集成支付宝快捷支付
- 让UIWebview拥有超强的图片处理能力
- 使用NSProxy和NSObject设计代理类的差异
- iOS学习笔记
- iOS发布新应用/更新新版本的流程
- cocos2dx -- tiledMap
- android拍照
- 李洪强iOS开发之计算数组的最大最小值
- android File的知识点一网打尽。
- [Android]一行代码加载GIF图
- 快速切换 hosts 文件的小程序:SwitchHosts
- Android集成支付宝步骤讲解
- [Android]仿IOS圆角AlertDialog
- <Android 基础(十一)> Snackbar
- <Android 基础(十一)> Snackbar