[Leetcode] 633. Sum of Square Numbers 解题报告
2018-01-20 11:22
330 查看
题目:
Given a non-negative integer
that a2 + b2 = c.
Example 1:
Example 2:
思路:
一个一个试了。这种题目最好是消除不必要的循环,并且少用开方和除法运算,这样可以大大提高效率。
代码:
class Solution {
public:
bool judgeSquareSum(int c) {
int half_c = (c >> 1), sb, b;
for (int a = 0; a * a <= half_c; ++a) {
sb = c - a * a;
b = sqrt(sb);
if (b * b == sb) {
return true;
}
}
return false;
}
};
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) {
int half_c = (c >> 1), sb, b;
for (int a = 0; a * a <= half_c; ++a) {
sb = c - a * a;
b = sqrt(sb);
if (b * b == sb) {
return true;
}
}
return false;
}
};
相关文章推荐
- [Leetcode] 40. Combination Sum II 解题报告
- 【LeetCode】1. Two Sum 解题报告
- LeetCode解题报告—— Bus Routes
- LeetCode-Best Time to Buy and Sell Stock II-解题报告
- [Leetcode] 670. Maximum Swap 解题报告
- LeetCode 新题: Find Minimum in Rotated Sorted Array II 解题报告-二分法模板解法
- 【LeetCode】Binary Tree Right Side View 解题报告
- [Leetcode] 674. Longest Continuous Increasing Subsequence 解题报告
- Leetcode 491. Increasing Subsequences 上升序列 解题报告
- LeetCode Convert Sorted List to Binary Search Tree 解题报告
- [Leetcode] 778. Swim in Rising Water 解题报告
- 【LeetCode】482. License Key Formatting 解题报告
- [Leetcode] 332. Reconstruct Itinerary 解题报告
- leetcode解题报告(23):Pascal's Triangle
- [Leetcode] 682. Baseball Game 解题报告
- [leetcode] 203. Remove Linked List Elements 解题报告
- [leetcode] 31. Next Permutation 解题报告
- LeetCode Intersection of Two Linked Lists 解题报告
- 【LeetCode】Text Justification 解题报告
- 【LeetCode】726.Number of Atoms(Hard)解题报告