LeetCode 2443. Sum of Number and Its Reverse Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2443. Sum of Number and Its Reverse

Description

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 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 <= 105

Solutions

Solution 1: Brute Force Enumeration

Enumerate k in the range [0,.., num], and check whether k + reverse(k) equals num.

The time complexity is O(n × log n), where n is the size of num.

PythonJavaC++GoTypeScriptRustC
class Solution: def sumOfNumberAndReverse(self, num: int) -> bool: return any(k + int(str(k)[::-1]) == num for k in range(num + 1))(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !