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

leetcode 202. Happy Number

2017-09-21 09:10 337 查看
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.



这道题按照最直接的方法做就可以了,注意判断出口条件。

代码如下:

import java.util.HashSet;
import java.util.Set;

/*
* 对这个数字的每个数位求平方和,如果如和为1或者平方和是之前出现过的就不进行求和,
* 根据最后的结果判断是不是一个开心数字。
*
* 这个问题很简单,但是需要仔细处理避免陷入无限的循环中,否者会超时
*
* */
public class Solution {
public boolean isHappy(int n)
{
Set<Integer> mySet=new HashSet<>();
while(true)
{
mySet.add(n);
int res=divide(n);
if(res==1)
return true;
else if(mySet.contains(res))
return false;
else
n=res;
}
}

int divide(int n)
{
int res=0;
while(n!=0)
{
int bit = n%10;
res+=bit*bit;
n=n/10;
}
return res;
}
}


下面是C++的做法,就是直接按照题意去做就可以了

代码如下:

#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <algorithm>

using namespace std;

class Solution
{
public:
bool isHappy(int n)
{
set<int> st;
while (true)
{
st.insert(n);
int res = devide(n);
if (res == 1)
return true;
else if (st.find(res) != st.end())
return false;
else
n = res;
}
return false;
}

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