题目描述

实现函数 int sqrt(int x).

计算并返回x的平方根(向下取整)

 

 

思路:

利用平方数的性质。连续n个奇数相加的结果一定是平方数。例如:

9 = 1+3+5 , 一共3个奇数相加,所以32= 9
16 = 1+3+5+7,一共4个奇数相加,所以42=16

public class SqrtMe {
    public static void main(String[] args) {
        int x = 9;
        SqrtMe sqrtMe = new SqrtMe();
        System.out.println(sqrtMe.sqrt(5));
    }

    /**
     *
     * @param x int整型
     * @return int整型
     */
    public int sqrt (int x) {

        int res = 0;
        int i = 1;
        while(x >= 0){
            x -= i;
            ++res;
            i +=2 ;
        }

        return res-1;
    }
}