Similar Problems

Similar Problems not available

Sum Of Number And Its Reverse - Leetcode Solution

Companies:

LeetCode:  Sum Of Number And Its Reverse Leetcode Solution

Difficulty: Medium

Topics: math  

Problem Statement:

The problem statement can be summarized as follows:

Given a non-negative integer n, calculate the sum of n and its reversed integer.

Example:

Input: 123 Output: 444 (123 + 321)

Approach:

We need to find the reverse of the given number and add it to the original number. We can do this by following these steps:

  1. Initialize a variable "reverse" to 0.

  2. While n is not equal to 0:

  • Find the last digit of n by using modulo operator: (n % 10)
  • Multiply the reverse by 10 and add the last digit: (reverse * 10 + (n % 10))
  • Divide n by 10 to remove the last digit: (n / 10)
  1. Add the original number and its reverse and return the result.

The implementation of the above approach in Python is as follows:

class Solution: def reverse(self, x: int) -> int: rev = 0

    while x != 0:
        digit = x % 10
        rev = rev * 10 + digit
        x = x // 10
    
    return rev
    
def reverseSum(self, n: int) -> int:
    return n + self.reverse(n)

Time Complexity:

The time complexity of our solution is O(log10 N) because the number of digits in the given number is equal to log10 N.

Space Complexity:

The space complexity of our solution is O(1) because we are not using any extra data structures. We are only using a few variables to store the original number, its reverse, and the last digit.

Sum Of Number And Its Reverse Solution Code

1