[Solved] A Number After a Double Reversal in Python

1 min read 213 words

The problem

Reversing an integer means to reverse all its digits.

For example, reversing 2021 gives 1202. Reversing 12300 gives 321 as the leading zeros are not retained. Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false.

Example 1:

Input: num = 526
Output: true
Explanation: Reverse num to get 625, then reverse 625 to get 526, which equals num.

Example 2:

Input: num = 1800
Output: false
Explanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num.

Example 3:

Input: num = 0
Output: true
Explanation: Reverse num to get 0, then reverse 0 to get 0, which equals num.

Constraints:

`0 <= num <= 106``

The solution

Option 1:

class Solution:
    def isSameAfterReversals(self, num: int) -> bool:
        return num == 0 or num % 10 != 0

Option 2:

class Solution:
    def isSameAfterReversals(self, num: int) -> bool:
        def reverse(number):
            result = 0
            while number:
                result = result * 10 + number % 10
                number //= 10
            return result

        return reverse(reverse(num)) == num 

Option 3:

class Solution:
    def isSameAfterReversals(self, num: int) -> bool:
        s = str(num)
        s1 = int(s[::-1])
        s2 = str(s1)
        print(s2[::-1])
        return int(s2[::-1])==int(s)

Test cases

526
1800
0
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts