633:平方数之和

This commit is contained in:
huangge1199 2021-04-28 09:52:26 +08:00
parent d3bac1c7f0
commit 837c116794
3 changed files with 136 additions and 1 deletions

View File

@ -0,0 +1,93 @@
//给定一个非负整数 c 你要判断是否存在两个整数 a b使得 a2 + b2 = c
//
//
//
// 示例 1
//
// 输入c = 5
//输出true
//解释1 * 1 + 2 * 2 = 5
//
//
// 示例 2
//
// 输入c = 3
//输出false
//
//
// 示例 3
//
// 输入c = 4
//输出true
//
//
// 示例 4
//
// 输入c = 2
//输出true
//
//
// 示例 5
//
// 输入c = 1
//输出true
//
//
//
// 提示
//
//
// 0 <= c <= 231 - 1
//
// Related Topics 数学
// 👍 195 👎 0
package leetcode.editor.cn;
//633:平方数之和
public class SumOfSquareNumbers {
public static void main(String[] args) {
//测试代码
Solution solution = new SumOfSquareNumbers().new Solution();
//true
System.out.println(solution.judgeSquareSum(5));
//false
System.out.println(solution.judgeSquareSum(3));
//true
System.out.println(solution.judgeSquareSum(4));
//true
System.out.println(solution.judgeSquareSum(2));
//true
System.out.println(solution.judgeSquareSum(1));
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean judgeSquareSum(int c) {
int num = (int) Math.sqrt(c);
int i = num;
while (i >= Math.sqrt(c - num * num)) {
if (c == i * i) {
return true;
}
int num1 = (int) Math.sqrt(c - i * i);
if (i * i + num1 * num1 == c) {
return true;
}
i--;
}
return false;
// // 官方
// for (long a = 0; a * a <= c; a++) {
// double b = Math.sqrt(c - a * a);
// if (b == (int) b) {
// return true;
// }
// }
// return false;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,42 @@
<p>给定一个非负整数&nbsp;<code>c</code>&nbsp;,你要判断是否存在两个整数 <code>a</code><code>b</code>,使得&nbsp;<code>a<sup>2</sup> + b<sup>2</sup> = c</code></p>
<p>&nbsp;</p>
<p><strong>示例 1</strong></p>
<pre><strong>输入:</strong>c = 5
<strong>输出:</strong>true
<strong>解释:</strong>1 * 1 + 2 * 2 = 5
</pre>
<p><strong>示例 2</strong></p>
<pre><strong>输入:</strong>c = 3
<strong>输出:</strong>false
</pre>
<p><strong>示例 3</strong></p>
<pre><strong>输入:</strong>c = 4
<strong>输出:</strong>true
</pre>
<p><strong>示例 4</strong></p>
<pre><strong>输入:</strong>c = 2
<strong>输出:</strong>true
</pre>
<p><strong>示例 5</strong></p>
<pre><strong>输入:</strong>c = 1
<strong>输出:</strong>true</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 &lt;= c &lt;= 2<sup>31</sup> - 1</code></li>
</ul>
<div><div>Related Topics</div><div><li>数学</li></div></div>\n<div><li>👍 195</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long