Leetcode[202] Happy Number
16 Nov 2015###Task1 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
###Python
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
used = set()
while n not in used:
used.add(n)
if n == 1:
return True
n = self.sumDig(n)
return False
def sumDig(self, n):
li = []
while n > 0:
li.append(n % 10)
n /= 10
ret = 0
for i in range(len(li)):
ret += li[i] * li[i]
return ret
###Java
public class Solution {
public int[] getBits(int n) {
String s = String.valueOf(n);
int[] bits = new int[s.length()]; //clever
int i = 0;
while (n > 0) {
bits[i++] = n % 10;
n /= 10;
}
return bits;
}
public int getSqrSum(int n) {
int res = 0;
int[] bits = getBits(n);
for (int i = 0; i < bits.length; i++) {
res += Math.pow(bits[i], 2);
}
return res;
}
public boolean isHappy(int n) {
HashSet<Integer> set = new HashSet<Integer>();
while (!set.contains(n)) {
set.add(n);
n = getSqrSum(n);
if (n == 1) {
return true;
}
}
return false;
}
}
###Points
- The key is: if not happy –> then there will be a loop –> how to detect loop? –> set()