“This is the first day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021”

Topic:

633. Sum of squares

Given a non-negative integer c, you need to determine whether there are two integers A and b such that a2 + b2 = c.

Example 1:

Input: c = 5 Output: true Description: 1 * 1 + 2 * 2 = 5Copy the code

Example 2:

Input: c = 3 Output: falseCopy the code

Example 3:

Input: c = 4 Output: trueCopy the code

Example 4:

Input: c = 2 Output: trueCopy the code

Example 5:

Input: c = 1 Output: trueCopy the code

 

Tip:

  • 0 <= c <= 231 - 1

Ideas:

  1. Take the square root of the current number, round it down, and call it thetasqrt
  2. from0Start traversing tosqrtwithsetThe square of each digit is written ascur
  3. Record the square of each digit at the same time sqrt - curIs the value of. If yes, yes
  4. If the traversal is complete, it does not exist

Implementation:

/ * * *@param {number} c
 * @return {boolean}* /
 var judgeSquareSum = function (c) {
  let sqrt = Math.floor(Math.sqrt(c));
  let set = new Set(a);for (let i = 0; i <= sqrt; i++) {
    let cur = c - i * i;
    set.add(i * i);

    if (set.has(cur)) {
      return true; }}return false;
};
Copy the code

If you understand it, you can click on it and see you in the next topic. If there is no accident after the article will be in this form, there are good suggestions welcome to comment area.