Sum of Number and Its Reverse Problem
#2443
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2443.
Given a non-negative integer num, 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, where 271 is the reverse of 172. Therefore, 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. Therefore, we return false.
Example 3:
Input: num = 181
Output: true
Explanation:
140 + 041 = 181, where 041 represents 41, the reverse of 140. Reversed numbers may contain leading zeros. Therefore, we return true.
Constraints:
0 <= num <= 10^5
Solution
Approach: Brute Force
Try every k from 0 to num and check whether k plus its reversal equals num. Since k + reverse(k) >= k, no larger k can work.
Complexity: O(num log num) time (reversing a number takes time proportional to its digits) and O(1) space.
class Solution:
def sumOfNumberAndReverse(self, num: int) -> bool:
return any(k + int(str(k)[::-1]) == num for k in range(num + 1))