【Java】国家予算
今回の問題は10兆円など膨大な数の処理を行う問題です。
「int」や「double」、「long」などで膨大な数を扱おうとすると数が壊れて出力されます。そこで使用するのは「BigDecimal」です。「BigInteger」でも良いのですが、今回は「BigDecimal」を使用します。二つの数値が与えられるので、その二つの数値の和が80桁を超えたら「overflow」を出力し、超えない場合は和を出力します。以下コードです。
import static java.lang.System.out;
import static java.lang.Integer.parseInt;
import java.math.BigDecimal;
import volume0.BaseExe;
public class NationalBudget extends BaseExe {
public static void main(String[] args) {
new NationalBudget().exeSysIn();
}
@Override
protected void execute() throws Exception {
int dataCount = parseInt(nextLine());
for (int count = 0; count < dataCount; count++) {
BigDecimal x = new BigDecimal(nextLine());
BigDecimal y = new BigDecimal(nextLine());
BigDecimal sum = x.add(y);
if (sum.precision() > 80) {
out.println("overflow");
} else {
out.println(sum);
}
}
}
}
二つの数値をBigDecimal型で受け取り、その和が80桁かを判定し出力を分岐させています。テストドライバは以下になります。
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import volume0.BaseTest;
public class NationalBudgetTest extends BaseTest {
private NationalBudget nb;
@Before
public void setUp() throws Exception {
super.setUp();
nb = new NationalBudget();
}
@After
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void test() {
nb.exeFileIn("./data/volume0_0015/in.txt");
assertOutList("./data/volume0_0015/out.txt");
}
}
テストドライバ内で使用している「in.txt」・「out.txt」は以下になります。
in.txt
6
1000
800
9999999999999999999999999999999999999999
1
99999999999999999999999999999999999999999999999999999999999999999999999999999999
1
99999999999999999999999999999999999999999999999999999999999999999999999999999999
0
100000000000000000000000000000000000000000000000000000000000000000000000000000000
1
100000000000000000000000000000000000000000000000000000000000000000000000000000000
100000000000000000000000000000000000000000000000000000000000000000000000000000000
out.txt
1800
10000000000000000000000000000000000000000
overflow
99999999999999999999999999999999999999999999999999999999999999999999999999999999
overflow
overflow
今回の問題は以下にあります。
アルゴリスムで困った時は、以下の本を参考にしてます。Javaに置き換えるのが少々難解ですが、、、
固有処理の基底クラスは以下の記事に記載していますので、参考にしてください。
テストドライバで継承しているクラスは以下の記事に記載していますので、参考にしてみてください。