朝活 アウトプット

入力される1~最大1000桁の数字の文字列を計算する問題で何も考えずにint や longを使って、エラーになった話。

型の範囲を超える計算なんて想定していなかったが、教科書なんかではこうした型の範囲に関して初期段階から出てくる。

int (4byte)  -2147483648 ~ 2147483647 

long(64byte)  -9223372036854775808 ~ 9223372036854775807 

 

この型の範囲を超えている数字を代入できないので、1000桁の数字の文字列として受け取って、とりあえず4桁ずつ区切る(10000進法の数字で)ことでまず考えてみたが、、、

10000で割った数字を1の位、次を10の位と計算して行けば良いのですが、問題は割る元となる数字が代入できないので、計算ができないことがそもそも問題だった。。。

 

ですので、.length()で桁数を確認した上で、.substring()のstartIndexをlength()-4, stopIndexをlength()として得た数字を配列に格納し、startIndexを-4、stopIndexに前のstartIndexを代入するstartIndex>=0の範囲で数字を取得する方法をまず考えた。

String s = sc.nextLine();
int t = Integer.parseInt(sc.nextLine());

int len = s.length();
int startIndex = len-4;
int stopIndex = len;
ArrayList<String> array = new ArrayList<>();
while(startIndex>=0) {
String num = s.substring(startIndex, stopIndex);
//System.out.println(num);
array.add(num);
stopIndex = startIndex;
startIndex = startIndex - 4;
if(startIndex<0) {
//System.out.println(s.substring(0, stopIndex));
array.add(s.substring(0, stopIndex));
}
}
for(int i=0; i<array.size(); i++){
int x = Integer.parseInt(array.get(i));
    //parseIntがここでは何故か働かない。
}

課題が一つ見つかりましたが、まだ分かっていない。ここは要チェック必要です。

ArrayListの方をIntegerにして、代入する時にparseIntしてみた時はwhileで回す分は問題なく動きますが、if文の中のparseIntではエラーになる??

明示的な変換をしては行けないのだろうか?

 

ただ、もっと調べてみると便利なものがありますね、、math.BigIntegerクラスが使えるみたいで、グッと楽に計算できます。大きな数字の文字列の四則演算を可能にします。

import java.math.BigInteger;

public class Main {
public static void main(String[] args) {
//Sは最大1000桁(数字の)文字列
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
BigInteger S = new BigInteger(s);
//BigInteger S = new BigInteger("123456789987654321123456789987654321123456789987654321123456789987654321");
//Tは1桁(数字の)文字列
String t = sc.nextLine();
BigInteger T = new BigInteger(t);
//BigInteger T = new BigInteger("5");
S = S.multiply(T);
System.out.println(S);
}
}