When To Stop When Number Is Not A Happy Number
Solution 1:
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.
defisHappy(x):
whileTrue:
if x == 1:
returnTrueif x == 4:
returnFalse
x = nextNumberInSequence(x)
Solution 2:
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.
Solution 3:
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.
Solution 4:
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
publicstaticboolean 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)) {
returnfalse;
}
seen.add(sum);
n = sum;
}
returntrue;
}
Post a Comment for "When To Stop When Number Is Not A Happy Number"