zoukankan      html  css  js  c++  java
  • LeetCode 69. Sqrt(x)

    原题链接在这里:https://leetcode.com/problems/sqrtx/

    题目:

    Implement int sqrt(int x).

    Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

    Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

    Example 1:

    Input: 4
    Output: 2
    

    Example 2:

    Input: 8
    Output: 2
    Explanation: The square root of 8 is 2.82842..., and since 
                 the decimal part is truncated, 2 is returned.

    题解:

    先找middle = (left + right)/2, middle^2 和 x 比较,比x小就在middle 和 right这段找,反之亦然。

    Note:1. middle 要设为long, 否则middle * middle 可能overflow

    2. while loop的条件是l<=r, 不是< e.g. x = 2

    3. return 别忘了加cast

    4. 即使这不是一个perfect square 也是返回right, 因为此时right就是那个较小的值.

    Time Complexity: O(logx). Space: O(1).

    AC Java:

     1 public class Solution {
     2     public int mySqrt(int x) {
     3         if(x<0){
     4             throw new IllegalArgumentException("Invalid input.");
     5         }
     6         
     7         long l = 0; 
     8         long r = x;
     9         while(l<=r){
    10             long mid = l+(r-l)/2;
    11             if(mid*mid > x){
    12                 r = mid-1;
    13             }else if(mid*mid < x){
    14                 l = mid+1;
    15             }else{
    16                 return (int)mid;
    17             }
    18         }
    19         return (int)r;
    20     }
    21 }

    类似Pow(x, n)Valid Perfect Square

  • 相关阅读:
    oracle中的游标
    Oracle中的表空间
    Oracle中建表及表操作
    oracle中的权限管理
    oracle中的数据类型
    Oracle中常用的系统函数
    oracle中的dual表简介
    Oracle中常用的系统表
    Git常用命令总结
    Git配置文件与git config命令
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824957.html
Copyright © 2011-2022 走看看