If a number is ' happy ' for this process ends in 1are a happynumber 1 2 + 92 = 8282 + 22 = 6862 + 82 = 10012 + 02 + 02 = 1
First Time:not good, when I-try to get-to-the-most significant bit, I-define current bit called cur, and cur *= all t Ime. This might gives rise to overflow on line when cur * 10. To overcome this I has to define cur to be a long.
The best-of-the-digit is-to-use n%10, and N-/=10 each loop. Dividing'll avoid unnecessary overflow.
BTW, no need to define a ArrayList to store all the digits.
1 Public classSolution {2 Public BooleanIshappy (intN) {3 if(n <= 0)return false;4 if(n = = 1)return true;5Hashset<integer> set =NewHashset<integer>();6 while(!set.contains (n)) {7 Set.add (n);8 LongCur = 1;9arraylist<integer> digits =NewArraylist<integer>();Ten intsum = 0; One while(N/cur >= 1) { ADigits.add ((int) (n% (cur*10)/cur)); -Cur *= 10; - } the for(intdigit:digits) { -Sum + = (int) Math.pow (digit, 2); - } -n =sum; + if(n = = 1)return true; - } + return false; A } at}
About syntax, line + it is correct to write it as:sum + = Math.pow (digit, 2),
But it's incorrect as:sum = sum + math.pow (digit, 2), should write as Sum = sum + (int) Math.pow (digit, 2)
So better cast pow to integer before use it.
Second Time:better
The best-of-the-digit is-to-use n%10, and N-/=10 each loop.
1 Public classSolution {2 Public BooleanIshappy (intN) {3 if(n <= 0)return false;4 if(n = = 1)return true;5Hashset<integer> set =NewHashset<integer>();6 while(!set.contains (n)) {7 Set.add (n);8 intsum = 0;9 while(N > 0) {TenSum + = (int) Math.pow (N%10, 2); OneN/= 10; A } -n =sum; - if(n = = 1)return true; the } - return false; - } -}
Leetcode:happy number