Sum of Number and Its Reverse
MediumUpdated: Aug 2, 2025
Practice on:
Problem
Given a non-negative integer num, return true ifnum _can be expressed as the sum of anynon-negative integer and its reverse, or _false otherwise.
Examples
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.
Constraints
0 <= num <= 10^5
Solution
Approach
Try all possible x from 0 to num. For each x, check if x + reverse(x) == num. If so, return true. Otherwise, return false.
Code
C++
class Solution {
public:
bool sumOfNumberAndReverse(int num) {
for (int x = 0; x <= num; ++x) {
int y = 0, t = x;
while (t) { y = y * 10 + t % 10; t /= 10; }
if (x + y == num) return true;
}
return false;
}
};
Java
class Solution {
public boolean sumOfNumberAndReverse(int num) {
for (int x = 0; x <= num; ++x) {
int y = 0, t = x;
while (t > 0) { y = y * 10 + t % 10; t /= 10; }
if (x + y == num) return true;
}
return false;
}
}
Kotlin
class Solution {
fun sumOfNumberAndReverse(num: Int): Boolean {
for (x in 0..num) {
var y = 0
var t = x
while (t > 0) {
y = y * 10 + t % 10
t /= 10
}
if (x + y == num) return true
}
return false
}
}
Python
class Solution:
def sumOfNumberAndReverse(self, num: int) -> bool:
for x in range(num+1):
y = int(str(x)[::-1])
if x + y == num:
return True
return False
Rust
impl Solution {
pub fn sum_of_number_and_reverse(num: i32) -> bool {
for x in 0..=num {
let mut y = 0;
let mut t = x;
while t > 0 {
y = y * 10 + t % 10;
t /= 10;
}
if x + y == num { return true; }
}
false
}
}
TypeScript
function sumOfNumberAndReverse(num: number): boolean {
for (let x = 0; x <= num; ++x) {
let y = 0, t = x;
while (t > 0) {
y = y * 10 + t % 10;
t = Math.floor(t / 10);
}
if (x + y === num) return true;
}
return false;
}
Complexity
- ⏰ Time complexity:
O(n log n) - 🧺 Space complexity:
O(1)