|
| 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 | +} |
0 commit comments