题解 | #求平方根#

求平方根

http://www.nowcoder.com/practice/09fbfb16140b40499951f55113f2166c

遍历,当res的平方大于x立即退出,然后返回--res值。

import java.util.*;


public class Solution {
    /**
     * 
     * @param x int整型 
     * @return int整型
     */
    public int sqrt (int x) {
        // write code here
        int res = 0;
        // 注意转换为 long, 否则会产生溢出
        while ((long)res*res <= x) {
            ++res;
        }
        return --res;
    }
}
       
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务