public class Solution {
public boolean isHappy(int n) {
HashSet set = new HashSet();
while (!set.contains(n))
{
set.add(n);
n = sum(getDigits(n));
if ( n ==1 )
{
return true;
}
}
return false;
}
private int sum (int[] arr)
{
int sum = 0;
for ( int i: arr)
{
sum+= i*i;
}
return sum;
}
private int[] getDigits(int n)
{
String s = String.valueOf(n);
int[] result = new int[s.length()];
int i = 0;
while ( n > 0 )
{
int m = n%10;
result[i++] = m;
n = n/10;
}
return result;
}
}
Wednesday, July 8, 2015
07/08 [hash]Happy Number
/*
Time:O(); Space:O()
Logic:
1. perform calculation of a^2 ++ b^2
2. record the value of a^2 ++ b^2 in the HashSet
*/
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment