LeetCode202——Happy Number快乐数
2015-08-03 10:33
483 查看
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
实现:
bool isHappy(int n) {
vector<int> result;
int val = getSquareSum(n);
while (val != 1) {
if (std::find(result.begin(), result.end(), val) != result.end()) {
return false;
}
result.push_back(val);
val = getSquareSum(val);
}
return true;
}
int getSquareSum(int n) {
int val = 0;
while (n) {
int rem = n%10;
val += rem*rem;
n = n / 10;
}
return val;
}
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
实现:
bool isHappy(int n) {
vector<int> result;
int val = getSquareSum(n);
while (val != 1) {
if (std::find(result.begin(), result.end(), val) != result.end()) {
return false;
}
result.push_back(val);
val = getSquareSum(val);
}
return true;
}
int getSquareSum(int n) {
int val = 0;
while (n) {
int rem = n%10;
val += rem*rem;
n = n / 10;
}
return val;
}
相关文章推荐
- HDU 5119 Happy Matt Friends - DP
- 在QML webview中使用alert及confirm Dialogs
- 我是如何自学Android,资料分享(2015 版)
- ios项目中引用其他开源项目
- android 混淆
- 【Android】TypedArray和obtainStyledAttributes使用(R.styleable.xx_xx)
- activity中 调用startActivityForResult的步骤及生命周期
- [Android][细节][布局]View的getDrawingCache()方法不会在bitmap的透明区域绘制该View下方的View
- iOS开发 线程计时器
- UnityException: Launching iOS project via Xcode failed. Check editor log for details
- [深入理解Android卷二 全文-第一章]开发环境部署
- Sandbox 沙盒
- Unity5灯光烘焙与Unity4 灯光烘焙实际应用中的差别
- iOS开发系列--Objective-C之KVC、KVO
- objective-c 中随机数的用法 (3种:arc4random() 、random()、CCRANDOM_0_1() )
- 可动态布局的android抽屉效果
- android中文件操作的四种枚举
- [Android]ScrollView和ListView上方的headView的下拉放大效果-PullZoomView的使用篇
- 【Unity】从Profile中窥探Unity的内存管理
- hdu 1452 happy 2004