Menu Close

Program to check Sum of Number and Its Reverse

Here, we will see Program to check Sum of Number and Its Reverse with code and algorithm.

You are given a non-negative integer num.

You have to return true if num can be expressed as the sum of any non-negative integer and its reverse, or false otherwise.

Example 1:

Input: num = 443
Output: true
Explanation: 172 + 271 = 443 so we return true.

Example 2:

Input: num = 63
Output: false
Explanation: 63 cannot be expressed as the sum of a non-negative integer and its reverse so we return false.

Example 3:

Input: num = 181
Output: true
Explanation: 140 + 041 = 181 so we return true. Note that when a number is reversed, there may be leading zeros.

Program to check sum of number and Its reverse code in C++

Code 1:

#include <iostream>
#include <unordered_map>
#include <vector>
#include <limits.h>

using namespace std;

int reverse(int n) {
    int sum = 0;
        
    while(n) {
        sum = sum * 10 + n % 10;
        n /= 10;
    }
    return sum;
}
    
bool sumOfNumberAndReverse(int num) {
    for(int i = 0; i <= num; i++) {
        // num == number + reverse(number)
        if(num == (i + reverse(i))) {
            return true;
        }
    }
    return false;
}
    
int main()
{
    cout<<sumOfNumberAndReverse(443);

    return 0;
}

Output:

1

To check more leetcode problem’s solution. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

Posted in C++, Medium

Leave a Reply

Your email address will not be published.

Contact Us