美文网首页每天一道leetcode之入门
Day.12 Sum of Square Numbers(63

Day.12 Sum of Square Numbers(63

作者: 前端伊始 | 来源:发表于2017-11-15 22:56 被阅读0次

问题描述
Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.
Example:

Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Input: 3
Output: False

思路:通过判断一个整数对1求模是否为0来判断一个数是否为整数。将双层循环变为一层

/**
 * @param {number} c
 * @return {boolean}
 */
var judgeSquareSum = function(c) {
    for(var i = 0; i*i <= c; i++){
      var val = Math.sqrt(c-i*i);
        if(val%1 === 0){
            return true;
        }
    }
    return false;
};

相关文章

网友评论

    本文标题:Day.12 Sum of Square Numbers(63

    本文链接:https://www.haomeiwen.com/subject/gehkvxtx.html