Skip to content

2119. A Number After a Double Reversal 👍

Approach 1: Naive

  • Time: $O(\log\texttt{num})$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  bool isSameAfterReversals(int num) {
    const int reversed1 = getReversed(num);
    const int reversed2 = getReversed(reversed1);
    return reversed2 == num;
  }

 private:
  int getReversed(int num) {
    int reversed = 0;
    while (num > 0) {
      reversed = reversed * 10 + num % 10;
      num /= 10;
    }
    return reversed;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public boolean isSameAfterReversals(int num) {
    final int reversed1 = getReversed(num);
    final int reversed2 = getReversed(reversed1);
    return reversed2 == num;
  }

  private int getReversed(int num) {
    int reversed = 0;
    while (num > 0) {
      reversed = reversed * 10 + num % 10;
      num /= 10;
    }
    return reversed;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def isSameAfterReversals(self, num: int) -> bool:
    def getReversed(num: int) -> int:
      reversed = 0
      while num > 0:
        reversed = reversed * 10 + num % 10
        num //= 10
      return reversed

    reversed1 = getReversed(num)
    reversed2 = getReversed(reversed1)
    return reversed2 == num

Approach 2: Heuristic

  • Time: $O(1)$
  • Space: $O(1)$
1
2
3
4
5
6
class Solution {
 public:
  bool isSameAfterReversals(int num) {
    return num == 0 || num % 10;
  }
};
1
2
3
4
5
class Solution {
  public boolean isSameAfterReversals(int num) {
    return num == 0 || num % 10 > 0;
  }
}
1
2
3
class Solution:
  def isSameAfterReversals(self, num: int) -> bool:
    return num == 0 or num % 10