Codewars Java练习:Find the next perfect square!

题目

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:

题解

Java的数学计算并没有内置到基本数据类型的成员函数中(否则int,long这类内置数据类型就没法参与运算了),而是集中到了Math包中。

将sq开方,并判断是否为整数,我的做法是把开方后的数强制转化为整形,然后平方检验。

当然,标准答案告诉我并不需要这么复杂,Java本身浮点数是支持取模运算,而对1取模可以用来判断是否是整数——

 

原创文章地址:【Codewars Java练习:Find the next perfect square!】,转载时请注明出处mhy12345.xyz

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据