zoukankan      html  css  js  c++  java
  • LeetCode OJ:Sqrt(x)(平方根)

    Implement int sqrt(int x).

    Compute and return the square root of x.

    简单的二分法,注意mid应该选为long,否则容易溢出:

     1 class Solution {
     2 public:
     3     int mySqrt(int x) {
     4         if(x == 0 || x == 1) return x;
     5         int beg = 1;
     6         int end = x;
     7         long mid = 0;   //这里用long,否则会溢出
     8         while(beg <= end){
     9             mid = beg + (end - beg)/2;
    10             if(mid * mid < x){
    11                 beg = mid + 1;
    12             }else if(mid * mid > x){
    13                 end = mid - 1;
    14             }else{
    15                 return mid;
    16             }
    17         }
    18         return end;
    19     }
    20 };
  • 相关阅读:
    centos5&6的启动过程
    linux之目录知识
    js动画
    js操作高级
    js操作
    JS基础
    跨域问题
    MySQL存储引擎
    MySQL索引管理
    MySQL操作命令
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4940670.html
Copyright © 2011-2022 走看看