題目描述

Java有8種基本資料型態(primitive data types),分別是char、boolean、byte、short、int、long、float和double。在這個題目中,我們會用到其中的整數型態(byte、short、int和long):



一個byte為8位元的有號整數。
一個short為16位元的有號整數。
一個int為32位元的有號整數。
一個long為64位元的有號整數。

輸入一個整數,判斷出這個整數可以被什麼樣的資料型態來儲存。

原題網址

輸入格式

第一行輸入測試資料數量T,接下來的T行分別輸入每個測試資料要測試的整數n。

輸出格式

若輸入的整數n有能夠將其儲存的資料型態,您必須將這些資料型態全部找出來,並用以下格式顯示:

n can be fitted in:
* dataType

如果整數n不能被byte、short、int或是long來儲存,用以下格式來輸出:

n can't be fitted anywhere.

範例輸入

5
-150
150000
1500000000
213333333333333333333333333333333333
-100000000000000

範例輸出

-150 can be fitted in:
* short
* int
* long
150000 can be fitted in:
* int
* long
1500000000 can be fitted in:
* int
* long
213333333333333333333333333333333333 can't be fitted anywhere.
-100000000000000 can be fitted in:
* long

額外解釋

−150可以被short、int和long來儲存。而213333333333333333333333333333333333則太大了,沒有辦法用基本的整數資料型態來儲存。

解題概念

要定義一個數值能不能被一個整數資料型態儲存,那就得看這個整數資料型態所能表示的數值範圍有多大。整數資料型態所能表示的數值與資料型態本身所使用幾個位元來表示數值有關,Java程式語言中數值的基本資料型態都是有號的(signed),也就是包含了正數和負數。以使用了32個位元來表示數值的int來說,一共可以表示232個數值,在2的補數系統中int可以表示的數值範圍是-231到231-1之間,剛好是232個數。

如果要將有號數的表示範圍轉成公式來計算,可以寫成這樣:

-2n-1 ~ 2n-1-1

其中的n為位元數量。

long是Java程式語言中可以表示出最多整數的基本資料型別。因此可以先將數值嘗試使用long來儲存,再來判斷數值的範圍是否可以被其他的整數資料型別來儲存。

參考答案

import java.util.Scanner;

public class Solution {

    public static void main(final String[] args) {

        final Scanner sc = new Scanner(System.in);
        final long n = Long.parseLong(sc.nextLine());
        for (int i = 0; i < n; ++i) {
            final String s = sc.nextLine();
            try {
                final long a = Long.parseLong(s);
                System.out.printf("%d can be fitted in:%n", a);
                if (a >= -128 && a <= 127) {
                    System.out.println("* byte");
                }
                if (a >= -32768 && a <= 32767) {
                    System.out.println("* short");
                }
                if (a >= -2147483648 && a <= 2147483647) {
                    System.out.println("* int");
                }
                System.out.println("* long");
            } catch (Exception ex) {
                System.out.printf("%s can't be fitted anywhere.%n", s);
            }

        }
    }
}