[leetcode]633. Sum of Square Numbers
2017-07-16 20:41
309 查看
题目链接:https://leetcode.com/problems/sum-of-square-numbers/#/description
Given a non-negative integer
that a2 + b2 = c.
Example 1:
Example 2:
Given a non-negative integer
c, your task is to decide whether there're two integers
aand
bsuch
that a2 + b2 = c.
Example 1:
Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3 Output: False
class Solution { public: bool judgeSquareSum(int c) { for(long a=0;a*a<=c;a++) { int b=c-(int)(a*a); if(binary_search(0,b,b)) return true; } return false; } bool binary_search(long s,long e,int n) { if(s>e) return false; long mid=s+(e-s)/2; if(mid*mid==n) return true; else if(mid*mid>n) return binary_search(s,mid-1,n); else if(mid*mid<n) return binary_search(mid+1,e,n); return false; } };
class Solution { public: bool judgeSquareSum(int c) { for(long long a=0;a*a<=c;a++) { int b=c-(long long)(a*a); if(binary_search(0,b,b)) return true; } return false; } private: bool binary_search(long long left,long long right,long long n) { while(left<=right) { long long mid=left+(right-left)/2; if(mid*mid==n) return true; else if(mid*mid>n) right=mid-1; else left=mid+1; } return false; } };
相关文章推荐
- leetcode 633. Sum of Square Numbers
- Leetcode 633. Sum of Square Numbers(Easy)
- leetcode 633. Sum of Square Numbers
- leetcode 633. Sum of Square Numbers 二分查找+勾股定理
- leetcode 633. Sum of Square Numbers
- 【leetcode】633. Sum of Square Numbers(Python & C++)
- LeetCode 633. Sum of Square Numbers
- [LeetCode]633. Sum of Square Numbers
- [Leetcode] 633. Sum of Square Numbers 解题报告
- LeetCode 633. Sum of Square Numbers
- [leetcode]633. Sum of Square Numbers
- LeetCode 633. Sum of Square Numbers
- LeetCode 633. Sum of Square Numbers
- 2017.12.25 LeetCode 633. Sum of Square Numbers【思维枚举】
- 633. Sum of Square Numbers
- 633. Sum of Square Numbers
- 633. Sum of Square Numbers。
- 633. Sum of Square Numbers (数学)
- LeetCode 633. Sum of Square Number
- 633. Sum of Square Numbers