-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathMysteryNumber.java
80 lines (62 loc) · 1.76 KB
/
MysteryNumber.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/* Below program checks if a number is a mystery number.
Mystery number - A number that can be represented by sum
of two numbers, such that the two numbers are reverse of
each other.*/
import java.util.*;
import java.lang.*;
public class MysteryNumber {
/* This function takes a number as a input and
returns a number with the digits reversed*/
static int reverse(int number) {
int rev = 0;
while(number != 0) {
rev *= 10;
rev += number % 10;
number = number / 10;
}
return rev;
}
// This function checks if the number is a mystery number
static int isMystery(int number) {
// We iterate till the middle of the number
for(int i = 1; i <= number / 2; i++) {
// Find reverse of current iteration value
int rev = reverse(i);
// Check the sum of number with its reverse
if(i + rev == number) {
// If its is equal to the given number we return and print
System.out.println("\nThe two digits are: " + i + " " + rev);
return 1;
}
}
// Else return -1
return -1;
}
public static void main(String args[]) {
// Taking number as input from the user
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int number = scan.nextInt();
scan.close();
// Calling the mystery function
int result = isMystery(number);
// If the result is 1, the number is a mystery number
if(result == 1) {
System.out.println("The given number " + number + " is a Mystery number.");
}
// Else it is not a mystery number
else {
System.out.println("\nThe given number " + number + " is not a Mystery number.");
}
}
}
/*
Sample I/O:
1)
Enter the number: 343
The two digits are: 122 221
The given number 343 is a Mystery number.
2)
Enter the number: 3214
The given number 3214 is not a Mystery number.
*/