x的平方根

来源:互联网 发布:淘宝宝贝详情教程 编辑:程序博客网 时间:2024/05/16 15:20

问题描述:

实现 int sqrt(int x) 函数,计算并返回 x 的平方根。

样例:

sqrt(3) = 1

sqrt(4) = 2

sqrt(5) = 2

sqrt(10) = 3

代码:



import java.util.Scanner;
import java.lang.Math;
public class Solution {
    /*
     * @param x: An integer
     * @return: The sqrt of x
     */
    public int sqrt(int x) {
        // write your code here
       /* if(x<0){
            throw new RuntimeException("平方数不能小于0");
        }
        int len;
       if(x%2==0){
           len=x/2;
       }else{
           len=x/2+1;
       } 
       int i=0;
        while(i<=len){
            if(i*i==x){
                return i;
            }
            if(i*i<x && (i+1)*(i+1)>x){
                return i;
            }
            i++;
        }*/
        return (int)Math.sqrt(x);
        
    }
    public static void main(String []args){
Solution s=new Solution();
        Scanner input=new Scanner(System.in);
        int num=input.nextInt();
        System.out.println(s.sqrt(num));
    }
}



原创粉丝点击