(1) 完美平方数

1. 问题描述

题目描述

2. 问题示例

问题示例

3. 代码实现-Python

class Solution:
    def numSquares(self, n):
        
        # 判断能被4整除
        while n % 4 == 0:   
            n //= 4   # 去整除4的个数
            
        #  判断能被8整除模7的情况    
        if n % 8 == 7:
            return 4  # 1+1+9+4 =15
        
        # 遍历情况
        for i in range(n + 1):
            temp = i * i
            if temp <= n:
                if int((n-temp) ** 0.5) ** 2 + temp == n:
                    return 1 + (0 if temp == 0 else 1)
            else:
                break
                
        return 3
    
# 主函数
if __name__ == '__main__':
    n = eval(input())
    print("初始值:", n)
    solution = Solution()
    print("结果:", solution.numSquares(n))

4. 结果

image.png

你可能感兴趣的:((1) 完美平方数)