Skip to main content
Back to problems
#633
Medium Algorithms

Sum of square numbers

Math Two Pointers Binary Search
36.7% acceptance
Feb 20, 2026
3441
619
Given a non-negative integer c, decide if there exist two integers a and b such that a^2 + b^2 = c.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn judge_square_sum(c: i32) -> bool {
    let c = c as i64;
    let mut a = 0i64;
    let mut b = (c as f64).sqrt() as i64;
    while a <= b {
      let sum = a * a + b * b;
      if sum == c {
        return true;
      } else if sum < c {
        a += 1;
      } else {
        b -= 1;
      }
    }
    false
  }
}