Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2443. Sum of Number and Its Reverse

MathEnumeration

Explanation:

To solve this problem, we need to iterate through all possible values up to half of the given number and check if the sum of the number and its reverse equals the given number. We can reverse a number by using modulo and division operations.

  1. Iterate from 0 to num/2.
  2. For each iteration, calculate the reverse of the current number.
  3. Check if the sum of the number and its reverse equals the given number.
  4. If a match is found, return true. Otherwise, return false at the end.

Time complexity: O(log(num)) - number of digits in num Space complexity: O(1) :

class Solution {
    public boolean isSumOfNumberAndReverse(int num) {
        for (int i = 0; i <= num / 2; i++) {
            int reverse = 0;
            int n = i;
            while (n > 0) {
                reverse = reverse * 10 + n % 10;
                n = n / 10;
            }
            if (i + reverse == num) {
                return true;
            }
        }
        return false;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.