633. Sum of Square Numbers

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

Example 3:

Input: c = 4
Output: true

Example 4:

Input: c = 2
Output: true

Example 5:

Input: c = 1
Output: true

 

Constraints:

  • 0 <= c <= 231 - 1

Rust Solution

struct Solution;

impl Solution {
    fn judge_square_sum(c: i32) -> bool {
        if c == 0 {
            return true;
        }
        let x = (c as f64).sqrt() as i32;
        for a in 0..=x {
            let bb = c - a * a;
            let b = (bb as f64).sqrt() as i32;
            if bb == b * b {
                return true;
            }
        }
        false
    }
}

#[test]
fn test() {
    assert_eq!(Solution::judge_square_sum(5), true);
    assert_eq!(Solution::judge_square_sum(3), false);
    assert_eq!(Solution::judge_square_sum(2_147_483_646), false);
}

Having problems with this solution? Click here to submit an issue on github.