LeetCode第69題_Sqrt(x)

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.




須注意當輸入是小於0的情況
都需直接回傳-1
1 返回1
0 返回0
-1 返回-1
-2 返回-1
...
依此類推


CODE


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package leetcode69_sqrt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author chous
 */
public class LeetCode69_Sqrt {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        BufferedReader input;
        input = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Input");
        String strInput = input.readLine();
        int numInput = Integer.parseInt(strInput);
        System.out.println(mySqrt(numInput));
    }
    
    public static int mySqrt(int x){
        if(x==1 || x==0)
            return x;
        for(long i=1;i<=x;i++){
            if(i*i > x)
                return (int)(i-1);
        }
        return -1;
    }
    
}




留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題