返回介绍

solution / 2400-2499 / 2443.Sum of Number and Its Reverse / README_EN

发布于 2024-06-17 01:03:06 字数 3918 浏览 0 评论 0 收藏 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 \times \log n)$, where $n$ is the size of $num$.

class Solution:
  def sumOfNumberAndReverse(self, num: int) -> bool:
    return any(k + int(str(k)[::-1]) == num for k in range(num + 1))
class Solution {
  public boolean sumOfNumberAndReverse(int num) {
    for (int x = 0; x <= num; ++x) {
      int k = x;
      int y = 0;
      while (k > 0) {
        y = y * 10 + k % 10;
        k /= 10;
      }
      if (x + y == num) {
        return true;
      }
    }
    return false;
  }
}
class Solution {
public:
  bool sumOfNumberAndReverse(int num) {
    for (int x = 0; x <= num; ++x) {
      int k = x;
      int y = 0;
      while (k > 0) {
        y = y * 10 + k % 10;
        k /= 10;
      }
      if (x + y == num) {
        return true;
      }
    }
    return false;
  }
};
func sumOfNumberAndReverse(num int) bool {
  for x := 0; x <= num; x++ {
    k, y := x, 0
    for k > 0 {
      y = y*10 + k%10
      k /= 10
    }
    if x+y == num {
      return true
    }
  }
  return false
}
function sumOfNumberAndReverse(num: number): boolean {
  for (let i = 0; i <= num; i++) {
    if (i + Number([...(i + '')].reverse().join('')) === num) {
      return true;
    }
  }
  return false;
}
impl Solution {
  pub fn sum_of_number_and_reverse(num: i32) -> bool {
    for i in 0..=num {
      if
        i +
          ({
            let mut t = i;
            let mut j = 0;
            while t > 0 {
              j = j * 10 + (t % 10);
              t /= 10;
            }
            j
          }) == num
      {
        return true;
      }
    }
    false
  }
}
bool sumOfNumberAndReverse(int num) {
  for (int i = 0; i <= num; i++) {
    int t = i;
    int j = 0;
    while (t > 0) {
      j = j * 10 + t % 10;
      t /= 10;
    }
    if (i + j == num) {
      return 1;
    }
  }
  return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文