problem:
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 and replace the number by the Sum of the squares of its digits, and repeat the process until the number equals 1 (where it would stay), or it loops Endl essly in a cycle which does not include 1. Those numbers for which this process ends in 1 is happy numbers.
Example:19 is a happy number
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
Analysis:
This problem is actually very very easy!The problem has actually described the algorithm very clearly! We just need to implement it!Choice:you want to DoAll those operations82:8^2 + 2^2 = 68In one step or not?If It is done with one step, in one loop, we need to first get each digit and sum the square of them together. The digit operation is always hard to implement compared with other logic, we should not mix them together. Why not separte those-major operation out?Step1: Get The digit array of a integer.Private int[] Get_array (intN) {String str=string.valueof (n); intLen =str.length (); int[] ret =New int[Len]; for(inti = 0; i < Len; i++) { intDigit_weight = (int) Math.pow (len-i-1); Ret[i]= N/Digit_weight; N= n%Digit_weight; } returnret; }skill:firstly convert N to String type, then we can get the length information through the Str.length (). String Str=string.valueof (n);intLen =str.length ();int[] ret =New int[Len]; Step2:sum each digit of theintarray together.Private intSumint[] a) {intRET = 0; for(inti = 0; i < a.length; i++) ret+ = a[i] *A[i]; returnret;} Main:according to the description, the number would end"1"or a circular digital sequence. If The circular situation happens, we definitely not want to avoid the infinite loop. With our old friend:hashset, we could easily achieve. HashSet<Integer> Hash_set =NewHashset<integer> (); while(!hash_set.contains (n)) {Hash_set.add (n); N=sum (Get_array (n)); if(n = = 1) return true; }return false;
Solution:
Public classSolution { Public BooleanIshappy (intN) {if(N < 0) Throw NewIllegalArgumentException ("The passed in N is negative!"); HashSet<Integer> Hash_set =NewHashset<integer> (); while(!hash_set.contains (n)) {Hash_set.add (n); N=sum (Get_array (n)); if(n = = 1) return true; } return false; } Private int[] Get_array (intN) {String str=string.valueof (n); intLen =str.length (); int[] ret =New int[Len]; for(inti = 0; i < Len; i++) { intDigit_weight = (int) Math.pow (len-i-1); Ret[i]= N/Digit_weight; N= n%Digit_weight; } returnret; } Private intSumint[] a) {intRET = 0; for(inti = 0; i < a.length; i++) ret+ = a[i] *A[i]; returnret; }}
[leetcode#202] Roman to Integer