高中生程式解題系統:大數運算 (Big Numbers Operations in Java)

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。

題目連結 http://zerojudge.tw/ShowProblem?problemid=a021

此題筆者用Java寫,因為Java有好用的 API BigInteger 阿。
用 Python 時,可以用eval函數。
基本上此題是用陣列來處理,此部分可參考 超長整數運算(大數運算)一文。

程式碼:
import java.util.Scanner;
import java.math.BigInteger;
public class JAVA {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
String op;
BigInteger a, b, c = null;
while (cin.hasNext()) {
a = cin.nextBigInteger();
op = cin.next();
b = cin.nextBigInteger();
if(op.equals("+") == true)
{
c = a.add(b);
}
else if(op.equals("-") == true)
{
c = a.subtract(b);
}
else if(op.equals("*") == true)
{
c = a.multiply(b);
}
else if(op.equals("/") == true)
{
c = a.divide(b);
}
System.out.println(c.toString());
}
}
}
view raw a021.java hosted with ❤ by GitHub

沒有留言: