Leetcode 633. Sum of Square Numbers(Easy)
2018-03-28 10:59
573 查看
1.题目
Given a non-negative integerc, your task is to decide whether there're two integers
aand
bsuch that a2 + b2 = c.翻译:给定一个非负整数 c ,你的任务是判断是否有两个整数 a 和 b ,使得a2 + b2 = c.Example 1:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3
Output: False
2.思路
超时思路:比较容易想到的就是,两层的循环,外侧循环 i 的区间是0到根号c,里层循环 j 的区间是 i到根号c。我已经尽力缩小区间,然而还是超时了。AC思路:之前有一个 回文判断 的题,是这样的思路,保留外层循环,然后逆向思维,看看剩下的数(c-i2)能不能被开根号。这样就只需要一层循环。判断数a能否被完全开方的方法就是,a开根号取整,再平方 是否和a相等。
3.算法
class Solution { public boolean judgeSquareSum(int c) { int sub=0; int pow; for(int i=0;i<=Math.sqrt(c);i++){ sub=c-(int)Math.pow(i,2); pow=(int)Math.pow((int)Math.sqrt(sub),2); if(pow==sub){ return true; } } return false; } }
4.总结
Math.sqrt()和Math.pow()返回值都是double,要强制转换成int,不然会提示报错。相关文章推荐
- 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(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
- 【LeetCode】107.Binary Tree Level Order Traversal II(Easy)解题报告
- leetcode 102 Binary Tree Level Order Traversal(难易度:Easy)
- Leetcode 118. Pascal's Triangle (Easy) (cpp)
- Leetcode 204. Count Primes (Easy) (cpp)
- LeetCode的easy题集合(C++实现)一
- Leetcode 226[easy]---Invert Binary Tree(迭代入门题,tree-queue,stack 入门题,反复看)
- 【LeetCode】(94)Binary Tree Inorder Traversal(Easy)