Strobogrammatic Number (I, II, III)

udpate Jan 23,2018 19:16

Strobogrammatic Number I

LeetCodearrow-up-right A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Write a function to determine if a number is strobogrammatic. The number is represented as a string.

For example the numbers "69", "88", and "818" are all strobogrammatic.

  • Solution

    符合条件的数一定只包含 [0, 1, 6, 8, 9] 这几个数,而且一定左右成对出现,可以先把每一对存入 HashMap,然后用双指针从左右向中间检查。

    • Java Code:

      class Solution {
          public boolean isStrobogrammatic(String num) {
              Map<Character, Character> map = new HashMap<>();
              map.put('0', '0');
              map.put('1', '1');
              map.put('8', '8');
              map.put('6', '9');
              map.put('9', '6');
              int l = 0, r = num.length() - 1;
              while (l <= r) {
                  Character value = map.get(num.charAt(l));
                  if (value == null || num.charAt(r) != value) return false;
                  l++;
                  r--;
              }
              return true;
          }
      }

Strobogrammatic Number II

LeetCodearrow-up-right

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

Find all strobogrammatic numbers that are of length = n.

For example,

  • Solution

      有两种思路,在中间插入和两边插入。如果选择每次在中间插入,就要注意当 n 为奇数的时候,当每个数字长度到达n-1后,最后一次只插入一个字符,而且是 [0,1,8] 中的一个。而如果选择两遍插入,则是对于技术情况不是从 "" 空字符串开始,而是从 [0, 1,8] 开始,每次两边插入一对组合。   具体实现的时候可以使用 iteration 和 recursion 两种实现方法。

    • Java Code (iteration):

    • Java Code (recursion)

      这里的思路是,如果n为奇数,则将res list 初始化为 [0,1,8],然后每次在每个数两侧添加各个pair; 如果是偶数,则直接在[""]的基础上开始;

Strobogrammatic Number III (To be continued)

LeetCodearrow-up-right

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

Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high.

For example, Given low = "50", high = "100", return 3. Because 69, 88, and 96 are three strobogrammatic numbers.

Note: Because the range might be a large number, the low and high numbers are represented as string.