您的位置:首页 > 移动开发

【leetcode】202. Happy Number

2016-06-11 10:36 453 查看
一、题目描述

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那么就是happy number,否则n等于每位的平方和,如果经过多次循环最后能得到1,那么该数也是happy number,否则不是happy number。

思路:(1)如果等于1,输出true

           (2)如果不等于,求每位的平方和

1.  等于1,输出true

2.  不等于1,且等于之前已出现过的整数,输出false

c++代码(8ms)

#include<iosteam>
#include<math>

class Solution {
public:
bool isHappy(int n) {
map<int, int> count;
while(n!=1){
if(count
> 0)
return false;
else
count
++;
n = cal(n);
}
return true;
}

int cal(int n){
//计算一个数每位的平方和
if(n<10 && n>=0)
return pow(n,2);
else{
int result = 0;
while(n){
result += pow(n%10, 2);
n/=10;
}
return result;
}
}
};


可以使用floyd判圈算法,暂时没太看懂,看懂了再更,先贴代码

代码1:

int digitSquareSum(int n) {
int sum = 0, tmp;
while (n) {
tmp = n % 10;
sum += tmp * tmp;
n /= 10;
}
return sum;
}

bool isHappy(int n) {
int slow, fast;
slow = fast = n;
do {
slow = digitSquareSum(slow);
fast = digitSquareSum(fast);
fast = digitSquareSum(fast);
} while(slow != fast);
if (slow == 1) return 1;
else return 0;
}

代码2:

int next(int n)
{
int res=0;
while (n)
{
int t = n % 10;
res += t*t;
n/=10;
}
return res;
}

bool isHappy(int n)
{
int i1=n, i2=next(n);

while ( i2 != i1)
{
i1 = next(i1);
i2 = next(next(i2));
}

return i1==1;
}


使用快指针、 慢指针法

思路:

新建一个快指针 和 慢指针

慢指针每次只求一次 下一个数;快指针 每次求两次 下一个数

如果

快指针的值 和 慢指针的值 相等,则返回 false

快指针的值等于 1 , 则返回 true

c++代码(3ms,20.74%)

class Solution {
public:
bool isHappy(int n) {
int fast = n;
int slow = n;
while(1){
fast = cal(cal(fast));
slow = cal(slow);
if(1 == fast){
return true;
}
if(fast == slow){
return false;
}
}
}

int cal(int n){
int res=0;
while(n){
res += pow(n%10, 2);
n/=10;
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: