The number whose sum if calculated to single digit turns out to be 1 then the number is called Magic number.
Example 1 :- 1234
1+2+3+4 = 10
1+0 = 1
Since we got the sum to be 1 hence 1234 is a Magic number.
Example 2 :- 7111
7+1+1+1 = 10
1+0 = 1
Sum turned out to be 1 hence 7111 is a magic number.
Example 3 :- 12345
1+2+3+4+5 = 15
1+5 = 6
Sum is 6 so 12345 is not a magic number.
Let us see how we can implement the logic for Magic number in Java. We will use 2 ways to code the logic. First method uses 2 nested loops. The second method uses single loop.
Method 1 (Easier to understand) :-
public class Tech4Humans {
public static void main(String[] args) {
int num = 7111;
boolean result = checkMagicNumber(num);
if (result) {
System.out.println(num + " is a magic number");
} else {
System.out.println(num + " is not a magic number");
}
}
static boolean checkMagicNumber(int num) {
int sum, tempNum = num;
do {
sum = 0;
while (tempNum > 0) {
sum = sum + (tempNum % 10);
tempNum = tempNum / 10;
}
tempNum = sum;
} while (sum > 9);
if (sum == 1) {
return true;
}
return false;
}
}
Output
7111 is a magic number
Method 2 (Cleaner Code and Single loop) :-
public class Tech4Humans {
public static void main(String[] args) {
int num = 1234;
boolean result = checkMagicNumber(num);
if (result) {
System.out.println(num + " is a magic number");
} else {
System.out.println(num + " is not a magic number");
}
}
static boolean checkMagicNumber(int num) {
int sum = 0, tempNum = num;
while (sum > 9 || tempNum > 0) {
if (tempNum == 0) {
tempNum = sum;
sum = 0;
}
sum = sum + (tempNum % 10);
tempNum = tempNum / 10;
}
if (sum == 1) {
return true;
}
return false;
}
}
Output
1234 is a magic number