- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathStrobogrammaticNumber.java
43 lines (36 loc) · 1.38 KB
/
StrobogrammaticNumber.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
packagecom.thealgorithms.maths;
importjava.util.HashMap;
importjava.util.Map;
/**
* A strobogrammatic number is a number that remains the same when rotated 180 degrees.
* In other words, the number looks the same when rotated upside down.
* Examples of strobogrammatic numbers are "69", "88", "818", and "101".
* Numbers like "609" or "120" are not strobogrammatic because they do not look the same when rotated.
*/
publicclassStrobogrammaticNumber {
/**
* Check if a number is strobogrammatic
* @param number the number to be checked
* @return true if the number is strobogrammatic, false otherwise
*/
publicbooleanisStrobogrammatic(Stringnumber) {
Map<Character, Character> strobogrammaticMap = newHashMap<>();
strobogrammaticMap.put('0', '0');
strobogrammaticMap.put('1', '1');
strobogrammaticMap.put('6', '9');
strobogrammaticMap.put('8', '8');
strobogrammaticMap.put('9', '6');
intleft = 0;
intright = number.length() - 1;
while (left <= right) {
charleftChar = number.charAt(left);
charrightChar = number.charAt(right);
if (!strobogrammaticMap.containsKey(leftChar) || strobogrammaticMap.get(leftChar) != rightChar) {
returnfalse;
}
left++;
right--;
}
returntrue;
}
}