LeetCode 0246. Strobogrammatic Number Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
0246. Strobogrammatic Number

Description

Given a string num which represents an integer, return true if num is a strobogrammatic number.

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

 

Example 1:

Input: num = "69"
Output: true

Example 2:

Input: num = "88"
Output: true

Example 3:

Input: num = "962"
Output: false

 

Constraints:

  • 1 <= num.length <= 50
  • num consists of only digits.
  • num does not contain any leading zeros except for zero itself.

Solutions

Solution 1: Two Pointers Simulation

We define an array d, where d[i] represents the number after rotating the digit i by 180°. If d[i] is -1, it means that the digit i cannot be rotated 180° to get a valid digit.

We define two pointers i and j, pointing to the left and right ends of the string, respectively. Then we continuously move the pointers towards the center, checking whether d[num[i]] and num[j] are equal. If they are not equal, it means that the string is not a strobogrammatic number, and we can directly return false. If i > j, it means that we have traversed the entire string, and we return true.

The time complexity is O(n), where n is the length of the string. The space complexity is O(1).

PythonJavaC++Go
class Solution: def isStrobogrammatic(self, num: str) -> bool: d = [0, 1, -1, -1, -1, -1, 9, -1, 8, 6] i, j = 0, len(num) - 1 while i <= j: a, b = int(num[i]), int(num[j]) if d[a] != b: return False i, j = i + 1, j - 1 return True(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !