when to stop when number is not a happy number

后端 未结 4 676
春和景丽
春和景丽 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:33

    As long as the current number has more than 3 digits, it's value decreases in the next iteration. When the number has 3 digits, the maximum value it can take in the next iteration is 3*81 <= 250. So use an array of size 250 and record all the numbers in the sequence that are less than 250. You can then easily detect if you have a duplicate.

    0 讨论(0)
  • 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<Integer> seen = new HashSet<Integer>();
    
              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;
    
        }
    
    0 讨论(0)
  • 2020-12-22 07:42

    You can detect unhappy numbers with a constant amount of memory. According to Wikipedia, for any positive integer starting point, the sequence will terminate at one, or loop forever at 4, 16, 37, 58, 89, 145, 42, 20, 4. Since no other loops exist, it is easy to test for unhappiness.

    def isHappy(x):
        while True:
            if x == 1:
                return True
            if x == 4:
                return False
            x = nextNumberInSequence(x)
    
    0 讨论(0)
  • 2020-12-22 07:58

    You would have to keep a record of all the numbers you have produced so far in the sequence, and if one of them comes up a second time you know you have a loop which will never reach 1. A set is probably a good choice for a place to store the numbers.

    0 讨论(0)
提交回复
热议问题