LeetCode 633. 平方数之和

题目

633. 平方数之和

描述

给定一个非负整数 c ,你要判断是否存在两个整数 ab,使得 a 2 + b 2 = c a^2 + b^2 = c

解题思路

  1. 判断c是否为非负整数,若是,则直接返回false

  2. 利用Math包中sqrt()方法求出小于c的平方根的最大整数作为右指针,同时设置左指针从0开始;

  3. 开始循环,若左指针小于右指针,判断两指针之和与c的大小;

  • 若和等于c,返回false;

  • 若和小于c,左指针加1;

  • 若和大于c,右指针减1;

  1. 默认返回false

实现

/**
 * Created with IntelliJ IDEA.
 * Version : 1.0
 * Author  : cunyu
 * Email   : [email protected]
 * Website : https://cunyu1943.github.io
 * Date    : 2020/3/20 9:49
 * Project : LeetCode
 * Package : PACKAGE_NAME
 * Class   : SixHundredThirtThree
 * Desc    : 633.平方数之和
 */
public class SixHundredThiryThree {
	public static void main(String[] args) {
		SixHundredThiryThree sixHundredThiryThree = new SixHundredThiryThree();
		int[] array = {3,5};
		for(int item:array){
//			System.out.println(item);
			System.out.println(sixHundredThiryThree.judgeSquareSum(item));
		}
	}

	public boolean judgeSquareSum(int c) {

		// c为非负整数,则若c为负直接返回false
		if (c < 0){
			return false;
		}
		// 取c的平方根,并将其强制转换为不大于平方根值的最大整数
		int flag = (int) Math.sqrt(c);
		int i = 0;
		while (i <= flag){
			if ((i*i + flag*flag) == c){
				return  true;
			} else if ((i * i + flag * flag) < c) {
				i++;
			}else {
				flag--;
			}
		}
		return false;
	}
}

发布了104 篇原创文章 · 获赞 69 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/github_39655029/article/details/104984997