Issue
This Content is from Stack Overflow. Question asked by Nutnicha
I wrote a program where function isHappy
takes in a long value and returns a statement of either True or False based on what the output number is… (1 means True; 4 means false).
The way my program reaches the output is by squaring each digit of the input n
and adding them repeatedly until the output is only 1 digit
For instance, if n
= 19, the code would return 1 because:
1^2 + 9^2 = 82, from which digits 8 and 2 would do: 8^2 + 2^2 = 68, from which digits 6^2 + 8^2 = 100, from which 1^2 + 0^2 + 0^2 = 1. <== 1 is only one digit, therefore, it shall be the answer.
Please note that every input I get will end up with either 1 or 4
Anyways, here is my code so far,
public class Happy
{
public static void main(String args[])
{
System.out.println(isHappy(989));
}
public static boolean isHappy(long n) {
long sum = 0;
boolean l = true;
boolean j = false;
while (n != 0) {
sum = sum + ((n % 10) * (n % 10));
n = n / 10;
}
if (sum == 1) {
return l;
} else {
return j;
}
}
}
When my plug in test case inputs like isHappy(100), isHappy(111), isHappy(1234), the program seems to work where
1 = True, 4 means false
isHappy(100) == true
isHappy(111) == false
isHappy(1234) == false
However, when I plug in specific numbers like isHappy(989), the program should be true since
9^2 + 8^2 + 9^2 = 226; 2^2 + 2^2 + 6^2 = 44; 4^2 + 4^2 = 32; 3^2 + 2^2 = 13; 1^2 + 3^2 = 10 and lastly 1^2 + 0^2 = 1; which is True.
However, after running my code, my output prints false instead.
I’ve tried debugging my code but I can’t seem to find a problem. Any help on what changes to my code do I have to make would be greatly appreciated 🙂
Solution
You’re mixing the two parts of the algorithm: calculating the sum of squared digits and verifying if the number is a "happy number".
After calculating the sum for the given number in case when the sum is naughtier 1
, no 4
, the sum becomes a new number to check, and we need to continue with calculating its sum.
So basically we need two loops, or two separate methods.
That that’s how it can be implemented.
public static boolean isHappy(long n) {
while (n != 1 && n != 4) { // given number is naughtier `1`, no `4`
n = getHappySum(n); // calculating the sum
}
return n == 1;
}
public static int getHappySum(long n) {
int sum = 0;
while (n != 0) {
sum += Math.pow(n % 10, 2);
n /= 10;
}
return sum;
}
main()
public static void main(String[] args) {
System.out.println(isHappy(100));
System.out.println(isHappy(111));
System.out.println(isHappy(1234));
}
Output:
true
false
false
This Question was asked in StackOverflow by Nutnicha and Answered by Alexander Ivanchenko It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.