Skip to content

Commit 07945c7

Browse files
authored
Add StrobogrammaticNumber (#4278)
1 parent 4fe419e commit 07945c7

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.thealgorithms.maths;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
/**
7+
* A strobogrammatic number is a number that remains the same when rotated 180 degrees.
8+
* In other words, the number looks the same when rotated upside down.
9+
* Examples of strobogrammatic numbers are "69", "88", "818", and "101".
10+
* Numbers like "609" or "120" are not strobogrammatic because they do not look the same when rotated.
11+
*/
12+
public class StrobogrammaticNumber {
13+
/**
14+
* Check if a number is strobogrammatic
15+
* @param number the number to be checked
16+
* @return true if the number is strobogrammatic, false otherwise
17+
*/
18+
public boolean isStrobogrammatic(String number) {
19+
Map<Character, Character> strobogrammaticMap = new HashMap<>();
20+
strobogrammaticMap.put('0', '0');
21+
strobogrammaticMap.put('1', '1');
22+
strobogrammaticMap.put('6', '9');
23+
strobogrammaticMap.put('8', '8');
24+
strobogrammaticMap.put('9', '6');
25+
26+
int left = 0;
27+
int right = number.length() - 1;
28+
29+
while (left <= right) {
30+
char leftChar = number.charAt(left);
31+
char rightChar = number.charAt(right);
32+
33+
if (!strobogrammaticMap.containsKey(leftChar) || strobogrammaticMap.get(leftChar) != rightChar) {
34+
return false;
35+
}
36+
37+
left++;
38+
right--;
39+
}
40+
41+
return true;
42+
}
43+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.thealgorithms.maths;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class StrobogrammaticNumberTest {
8+
9+
@Test
10+
void testIsStrobogrammatic() {
11+
StrobogrammaticNumber strobogrammaticNumber = new StrobogrammaticNumber();
12+
assertThat(strobogrammaticNumber.isStrobogrammatic("69")).isTrue();
13+
assertThat(strobogrammaticNumber.isStrobogrammatic("88")).isTrue();
14+
assertThat(strobogrammaticNumber.isStrobogrammatic("818")).isTrue();
15+
assertThat(strobogrammaticNumber.isStrobogrammatic("101")).isTrue();
16+
assertThat(strobogrammaticNumber.isStrobogrammatic("609")).isTrue();
17+
assertThat(strobogrammaticNumber.isStrobogrammatic("120")).isFalse();
18+
}
19+
}

0 commit comments

Comments
 (0)