Skip to content

1056. Confusing Number

  • Time: $O(\log n)$
  • Space: $O(\log n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  bool confusingNumber(int n) {
    const string s = to_string(n);
    const vector<char> rotated{'0', '1', 'x', 'x', 'x',
                               'x', '9', 'x', '8', '6'};
    string rotatedNum;

    for (int i = s.length() - 1; i >= 0; --i) {
      if (rotated[s[i] - '0'] == 'x')
        return false;
      rotatedNum += rotated[s[i] - '0'];
    }

    return rotatedNum != s;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public boolean confusingNumber(int n) {
    final String s = String.valueOf(n);
    final char[] rotated = {'0', '1', 'x', 'x', 'x', 'x', '9', 'x', '8', '6'};
    StringBuilder sb = new StringBuilder();

    for (int i = s.length() - 1; i >= 0; --i) {
      if (rotated[s.charAt(i) - '0'] == 'x')
        return false;
      sb.append(rotated[s.charAt(i) - '0']);
    }

    return !sb.toString().equals(s);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def confusingNumber(self, n: int) -> bool:
    s = str(n)
    rotated = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}
    rotatedNum = []

    for c in s[::-1]:
      if c not in rotated:
        return False
      rotatedNum.append(rotated[c])

    return ''.join(rotatedNum) != s