LeetCode 246: Strobogrammatic Number
LeetCode 246 Solution Explanation
Explanation
To solve this problem, we need to determine whether a given number is a strobogrammatic number. A strobogrammatic number is a number that looks the same when rotated 180 degrees.
We can create a mapping of valid strobogrammatic pairs: (0,0), (1,1), (6,9), (8,8), (9,6).
We iterate through the number from the start and end simultaneously, checking if the pair of digits at each position is a valid strobogrammatic pair. If they are not, we return false. If all pairs are valid, we return true.
Time complexity: O(N) where N is the number of digits in the input number. Space complexity: O(1)
LeetCode 246 Solutions in Java, C++, Python
class Solution {
public boolean isStrobogrammatic(String num) {
int left = 0, right = num.length()-1;
while (left <= right) {
if (!isValid(num.charAt(left), num.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
private boolean isValid(char c1, char c2) {
return (c1 == '0' && c2 == '0') || (c1 == '1' && c2 == '1') || (c1 == '6' && c2 == '9') || (c1 == '8' && c2 == '8') || (c1 == '9' && c2 == '6');
}
}
Interactive Code Editor for LeetCode 246
Improve Your LeetCode 246 Solution
Use the editor below to refine the provided solution for LeetCode 246. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...