返回介绍

solution / 0600-0699 / 0633.Sum of Square Numbers / README_EN

发布于 2024-06-17 01:03:36 字数 3179 浏览 0 评论 0 收藏 0

633. Sum of Square Numbers

中文文档

Description

Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.

 

Example 1:

Input: c = 5
Output: true
Explanation: 1 * 1 + 2 * 2 = 5

Example 2:

Input: c = 3
Output: false

 

Constraints:

  • 0 <= c <= 231 - 1

Solutions

Solution 1

class Solution:
  def judgeSquareSum(self, c: int) -> bool:
    a, b = 0, int(sqrt(c))
    while a <= b:
      s = a**2 + b**2
      if s == c:
        return True
      if s < c:
        a += 1
      else:
        b -= 1
    return False
class Solution {
  public boolean judgeSquareSum(int c) {
    long a = 0, b = (long) Math.sqrt(c);
    while (a <= b) {
      long s = a * a + b * b;
      if (s == c) {
        return true;
      }
      if (s < c) {
        ++a;
      } else {
        --b;
      }
    }
    return false;
  }
}
class Solution {
public:
  bool judgeSquareSum(int c) {
    long a = 0, b = (long) sqrt(c);
    while (a <= b) {
      long s = a * a + b * b;
      if (s == c) return true;
      if (s < c)
        ++a;
      else
        --b;
    }
    return false;
  }
};
func judgeSquareSum(c int) bool {
  a, b := 0, int(math.Sqrt(float64(c)))
  for a <= b {
    s := a*a + b*b
    if s == c {
      return true
    }
    if s < c {
      a++
    } else {
      b--
    }
  }
  return false
}
function judgeSquareSum(c: number): boolean {
  let a = 0,
    b = Math.floor(Math.sqrt(c));
  while (a <= b) {
    let sum = a ** 2 + b ** 2;
    if (sum == c) return true;
    if (sum < c) {
      ++a;
    } else {
      --b;
    }
  }
  return false;
}
use std::cmp::Ordering;
impl Solution {
  pub fn judge_square_sum(c: i32) -> bool {
    let c = c as i64;
    let mut left = 0;
    let mut right = (c as f64).sqrt() as i64;
    while left <= right {
      let num = left * left + right * right;
      match num.cmp(&c) {
        Ordering::Less => {
          left += 1;
        }
        Ordering::Greater => {
          right -= 1;
        }
        Ordering::Equal => {
          return true;
        }
      }
    }
    false
  }
}

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

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

发布评论

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