题目
You might know some pretty large perfect squares. But what about the NEXT one?
Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.
If the parameter is itself not a perfect square, than -1 should be returned. You may assume the parameter is positive.
Examples:
findNextSquare(121) --> returns 144
findNextSquare(625) --> returns 676
findNextSquare(114) --> returns -1 since 114 is not a perfect
题解
Java的数学计算并没有内置到基本数据类型的成员函数中(否则int,long这类内置数据类型就没法参与运算了),而是集中到了Math包中。
将sq开方,并判断是否为整数,我的做法是把开方后的数强制转化为整形,然后平方检验。
import java.util.*; import java.io.*; class NumberFun { public static long findNextSquare(long sq) { if (Math.pow((long)Math.sqrt(sq),2) != sq) return -1; return (long)Math.pow(Math.sqrt(sq)+1,2); } }
当然,标准答案告诉我并不需要这么复杂,Java本身浮点数是支持取模运算,而对1取模可以用来判断是否是整数——
public class NumberFun { public static long findNextSquare(long sq) { return Math.sqrt(sq) % 1 != 0 ? -1 : (long)Math.pow(Math.sqrt(sq)+1,2); } }