leetcode刷题系列----模式1(Two Points 双指针)- 633:Sum of Square Numbers平方数之和

这篇博客介绍了如何用Python、C++和Java解决判断一个数是否可以表示为两个整数平方和的问题。通过设置双指针并逐步调整,找到可能的平方数组合。代码简洁高效,适合初学者理解算法思想。

Tips:

  • 语言只是工具,建议使用平时科研中的语言作为首选,一般就是python。C++最好辅修,项目落地首选。其实在不涉及main函数时,核心的类或者函数算法思想极其相似。
  • 更多题解请见本系列目录

python

class Solution:
    def judgeSquareSum(self, c: int) -> bool:
        low, high = int(0), int(c**0.5)
        while low<=high:
            sumsqure = low**2 + high**2
            if sumsqure<c: low+=1
            elif sumsqure>c: high-=1
            else : return True
        return False

C++

class Solution {
public:
    bool judgeSquareSum(int c) {
        long low= 0;
        long high = long(sqrt(c));
        while(low<=high)
        {
            long sum = low*low + high*high;
            if (sum==c) return true;
            if (sum<c) ++low;
            if (sum>c) --high;
        }
        return false;
    }
};

Java

class Solution {
    public boolean judgeSquareSum(int c) {
        long low= 0;
        long high = (long) Math.sqrt(c);
        while(low<=high)
        {
            long sum = low*low + high*high;
            if (sum==c) return true;
            if (sum<c) ++low;
            if (sum>c) --high;
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值