LeetCode279——Perfect Squares

来源:互联网 发布:端口 英文 编辑:程序博客网 时间:2024/06/06 04:19

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


实现:
class Solution {
public:


    bool isSquare(int n) {
        int a = (int)sqrt(n);
        return a*a == n;
    }
    int numSquares(int n) {
        while ((n & 3) == 0) {
            n = n / 4;
        }
        if ((n & 7) == 7) return 4;
        if (isSquare(n)) return 1;
        int sq = (int) sqrt(n);
        for (int i = 1; i <=sq; i++) {
            if (isSquare(n -i*i))
                return 2;
        }
        return 3;
    }
};

0 0
原创粉丝点击