美文网首页
每日一练55——Java找到最近的平方数(8kyu)

每日一练55——Java找到最近的平方数(8kyu)

作者: 砾桫_Yvan | 来源:发表于2018-07-24 10:28 被阅读0次

题目

你的任务是找到一个正整数n的最近的平方数,nearest_sq(n)。

测试用例:

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class NearestSqTest {
    @Test
    public void basicTests() {
         assertEquals(1, CodeWarsMath.nearestSq(1));
         assertEquals(1, CodeWarsMath.nearestSq(2));
         assertEquals(9, CodeWarsMath.nearestSq(10));
         assertEquals(121, CodeWarsMath.nearestSq(111));
         assertEquals(10000, CodeWarsMath.nearestSq(9999));
    }
}

解题

My

我的笨方法再现江湖:

思路:
1.i从1开始方,直到i方大于n
2.再判断i方和(i-1)方相对n的差值大小
3.确定最接近的方值m

public class CodeWarsMath {
    public static int nearestSq(final int n) {
        int m = 0;
        for (int i = 1; i <= n; i++) {
            if (i * i > n) {
                if ((i * i - n) > (n - ((i - 1) * (i - 1)))) {
                    m = (i - 1) * (i - 1);
                    break;
                } else {
                    m = i * i;
                    break;
                }
            } else if (i * i == n) {
                m = i * i;
                break;
            }
        }
        return m;
    }
}

高手:

一句话

public class CodeWarsMath {
  public static int nearestSq(final int n){
    return (int) Math.pow(Math.round(Math.sqrt(n)),2);
  }
}

思路:
1.sqrt开方,即返回正确舍入的 double 值的正平方根;
2.round,传入double返回最接近参数的 long;
3.pow(x,y)即x的y次方。

后记

Math类挺好用的。

相关文章

网友评论

      本文标题:每日一练55——Java找到最近的平方数(8kyu)

      本文链接:https://www.haomeiwen.com/subject/lgqemftx.html