202. Happy Number
2016-06-24 22:50
330 查看
https://leetcode.com/problems/happy-number/
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
这道题定义了一种快乐数,就是说对于某一个正整数,如果对其各个位上的数字分别平方,然后再加起来得到一个新的数字,再进行同样的操作,如果最终结果变成了1,则说明是快乐数,如果一直循环但不是1的话,就不是快乐数,那么现在任意给我们一个正整数,让我们判断这个数是不是快乐数,题目中给的例子19是快乐数,那么我们来看一个不是快乐数的情况,比如数字11有如下的计算过程:
1^2 + 1^2 = 2
2^2 = 4
4^2 = 16
1^2 + 6^2 = 37
3^2 + 7^2 = 58
5^2 + 8^2 = 89
8^2 + 9^2 = 145
1^2 + 4^2 + 5^2 = 42
4^2 + 2^2 = 20
2^2 + 0^2 = 4
我们发现在算到最后时数字4又出现了,那么之后的数字又都会重复之前的顺序
可以用set来记录所有出现过的数字
class Solution {
public:
bool isHappy(int n) {
if(n<=0){
return false;
}
set<int> mul;
while(!mul.count(n)){
mul.insert(n);
int sum=0;
while(n){
sum+=(n%10)*(n%10);
n/=10;
}
if(sum==1){
return true;
}
n=sum;
}
return false;
}
};
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
这道题定义了一种快乐数,就是说对于某一个正整数,如果对其各个位上的数字分别平方,然后再加起来得到一个新的数字,再进行同样的操作,如果最终结果变成了1,则说明是快乐数,如果一直循环但不是1的话,就不是快乐数,那么现在任意给我们一个正整数,让我们判断这个数是不是快乐数,题目中给的例子19是快乐数,那么我们来看一个不是快乐数的情况,比如数字11有如下的计算过程:
1^2 + 1^2 = 2
2^2 = 4
4^2 = 16
1^2 + 6^2 = 37
3^2 + 7^2 = 58
5^2 + 8^2 = 89
8^2 + 9^2 = 145
1^2 + 4^2 + 5^2 = 42
4^2 + 2^2 = 20
2^2 + 0^2 = 4
我们发现在算到最后时数字4又出现了,那么之后的数字又都会重复之前的顺序
可以用set来记录所有出现过的数字
class Solution {
public:
bool isHappy(int n) {
if(n<=0){
return false;
}
set<int> mul;
while(!mul.count(n)){
mul.insert(n);
int sum=0;
while(n){
sum+=(n%10)*(n%10);
n/=10;
}
if(sum==1){
return true;
}
n=sum;
}
return false;
}
};
相关文章推荐
- Android使用achart绘图框架出现java.lang.NoClassDefFoundError错误解决方式
- Android Studio:如何使用Android Studio与夜神模拟器开发调试
- AndroidStudio使用技巧
- <Android 基础(七)> DrawerLayout and NavigationView
- Bitmap的二次采样
- Android 开发中的接口文档
- UIwebview加载本地html文件
- <Android 基础(七)> DrawerLayout and NavigationView
- ios获取沙盒路径
- 微信服务器发送三次重复的排重问题
- Android中init进程的工作
- Android如何在广播接收器中启动活动和弹出对话框
- ios多线程 - NSThread 简介
- android 异步任务AsyncTask
- android Merger 代替 FrameLayout:布局优化
- Android 查看内存使用工具 (procstats)
- Android 基于SurfaceTexture shader的类动漫+波浪形图像处理
- android Context深度剖析
- 详解Android中AsyncTask的使用
- 【转载】混编ObjectiveC++