leetcode 202: Happy Number
2015-08-26 12:20
429 查看
Use a set to save all visited numbers. If the new number is already in the set, then it will not end. And if the new number is 1, return true.
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> set;
while(set.find(n)==set.end())
{
set.insert(n);
n=calculate(n);
if(n==1)
return true;
}
return false;
}
int calculate(int n)
{
int res=0;
while(n)
{
res+=(n%10)*(n%10);
n/=10;
}
return res;
}
};
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> set;
while(set.find(n)==set.end())
{
set.insert(n);
n=calculate(n);
if(n==1)
return true;
}
return false;
}
int calculate(int n)
{
int res=0;
while(n)
{
res+=(n%10)*(n%10);
n/=10;
}
return res;
}
};
相关文章推荐
- iOS基础-高级视图-UITableView--实例:app管理
- Android反编译工具及用法
- 自己写Android图片缓存框架之二级disk缓存
- codeforces 348B B. Apple Tree(dfs+数论)
- 【JS/辨析】javascript 中的 apply 和 call 方法
- Quick-Cocos2d-x 3.3 Final的资源与脚本加密
- Android Volley源码分析
- have you declared this activity in your AndroidManifest.xml 解决办法
- Android中Java和JavaScript交互实例
- Android代码规范
- Android性能优化典范(一)
- 基于android的实时音频频谱仪
- Android 再按一次返回键退出的第三种方式
- 自定义搜索栏
- IOS设计模式:单例以及单例传值
- 从零开始学 iOS 开发的15条建议
- Android 获取手机设备等的信息
- Java Reference Objects or How I Learned to Stop Worrying and Love OutOfMemoryError
- To create my first app in iOS with Xcode(在Xcode创建我的第一个iOS app )
- ant单个或多个渠道包打包参考文档