美文网首页
Sum of Square Numbers

Sum of Square Numbers

作者: Jarhot | 来源:发表于2017-07-03 11:36 被阅读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 1:

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

    Example 2:

    Input: 3
    Output: False

        public boolean judgeSquareSum(int c) {
            int left = 0;
            for (int right = (int) Math.pow(2, 0.5) * (int) Math.pow(c, 0.5); right >= 0; right--) {
                while (right >= left) {
                    int count = (int) (Math.pow(left, 2) + Math.pow(right, 2));
                    if (count > c) {
                        break;
                    } else if (count < c) {
                        left++;
                    } else if (count == c) {
                        return true;
                    }
                }
            }
            return false;
        }
    

    第二种时间超时

        public boolean judgeSquareSum(int c) {
            for (int i = 0; i * i <= c; i++) {
                int left = c - i * i;
                int sqleft = (int) Math.pow(left, 0.5);
                if (sqleft * sqleft == left) {
                    return true;
                }
            }
            return false;
        }
    

    相关文章

      网友评论

          本文标题: Sum of Square Numbers

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