Sum of Number and Its Reverse - Problem

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.

The reverse of an integer is obtained by reversing the order of its digits. For example, the reverse of 123 is 321.

Example: If num = 443, we can express it as 181 + 181 (where 181 reversed is 181), so return true.

Input & Output

Example 1 — Palindromic Sum
$ Input: num = 443
Output: true
💡 Note: 443 can be expressed as 370 + 73, where 73 is the reverse of 370.
Example 2 — Simple Case
$ Input: num = 63
Output: true
💡 Note: 63 can be expressed as some number plus its reverse. For example, we need to find x where x + reverse(x) = 63.
Example 3 — Impossible Case
$ Input: num = 4
Output: true
💡 Note: 4 can be expressed as 2 + 2, where the reverse of 2 is 2.

Constraints

  • 0 ≤ num ≤ 106

Visualization

Tap to expand
Sum of Number and Its Reverse INPUT num = 443 (non-negative integer) Find: a + reverse(a) = 443 a number + rev(a) reverse = 443 Search range: 0 to 443 (a cannot exceed num) ALGORITHM STEPS 1 Initialize Loop for a = 0 to num (443) 2 Reverse Digits Calculate reverse of a 3 Check Sum if a + rev(a) == num 4 Return Result true if found, else false Example: a = 221 reverse(221) = 122 221 + 122 = 343 343 != 443, continue... Found: 172 + 271 = 443 FINAL RESULT true Solution exists! Valid Pair Found 172 + 271 172 + 271 = 443 Verification: reverse(172) = 271 172 + 271 = 443 [OK] Matches input! Key Insight: The search space is bounded: we only need to check values from 0 to num, since a + reverse(a) >= a. For each candidate a, reversing digits is O(log a). Total time complexity: O(num * log(num)). Space complexity is O(1) as we only store temporary variables for reversal calculation. TutorialsPoint - Sum of Number and Its Reverse | Mathematical Reverse Calculation
Asked in
Meta 25 Google 20
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen