LeetCode第367題_Valid Perfect Square


Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Returns: True
Example 2:
Input: 14
Returns: False




注意
-2 回傳 false
-1 回傳 false
0  回傳 false
1 回傳 true
2 回傳  false
4 回傳 true
16 回傳 true



然後一樣小心over flow 所以迴圈尋訪不用int 改用long
較保險

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
42
/*
 * 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 leetcode367_validperfectsquare;

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

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

    /**
     * @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(isPerfectSquare(numInput));
    }
    public static boolean isPerfectSquare(int num){
        if(num<=0)
            return false;
        if(num==1)
            return true;
        for(long i=1;i<=num;i++){
            if(i*i == num){
                return true;
            }
        }
        return false;
    }
}






留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

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