when to stop when number is not a happy number

后端 未结 4 677
春和景丽
春和景丽 2020-12-22 07:19

A happy number is 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 un

4条回答
  •  一生所求
    2020-12-22 07:34

    This method will return true , if given number is happy number or else it will return false. We are using set here to avoid infinite loop situation.

    Input: 19

    Output: true

    Explanation:

    1*1 + 9*9 = 82

    8*8 + 2*2 = 68

    6*6 + 8*8 = 100

    1*1 + 0*0 + 0*0 = 1

         public static boolean isHappy(int n) {
    
              Set seen = new HashSet();
    
              while(n != 1) {
                int current = n;
                int sum = 0;
                while(current != 0) {
                    sum += (current % 10) * (current % 10);
                    current /= 10;
                }
    
                if(seen.contains(sum)) {
                    return false;
                }
    
                seen.add(sum);
                n = sum;
            }
    
            return true;
    
        }
    

提交回复
热议问题