java高精度整数加减法_高精度问题——Java大数类~系列1——整数加法 hdu 1002

高精度问题(1)——整数加法

很多博客上都说用Java大数类解决高精度问题很方便,这两天有空就试了一下,发现真的很好用~一系列的大数问题都可以在Java的大数类里找到解决方法。

首先是整数加法问题,用C++的话要通过字符串来实现,有一点麻烦。但是Java因为有现成的大数类,函数都是封装好了直接用的,所以代码可以写的很短。

hdu 1002 原题如下:

A + B Problem II

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 167185    Accepted Submission(s): 31977

Problem Description

I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.

Input

The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.

Output

For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.

Sample Input

2

1 2

112233445566778899 998877665544332211

Sample Output

Case 1:

1 + 2 = 3

Case 2:

112233445566778899 + 998877665544332211 = 1111111111111111110

代码如下(注释写的比较详细,就不用另外解释了):

1 //1.大整数加法 ~java~ hdu 1002

2 import java.math.BigInteger; //大数类

3 import java.util.Scanner; //要从控制台输入信息,就要导入此包

4 import java.io.*; //是一组类,是在java.io包里的所有类5 //*是通配符,比如a*.txt代表的就是以a开头的所有txt文件

6

7 public class Main //建立一个公共的Main类

8 {9 public static voidmain(String[] args)10 {11 Scanner cin = new Scanner(System.in); //Scanner是可以使用正则表达式来分析基本类型和字符串的简单文本扫描器12 //System.in是来自控制台的输入

13 while(cin.hasNextInt())14 //cin.hasNextInt()属于java.util.Scanner这个类,针对int型数(下一个为true,继续)

15 {16 BigInteger ans, b, c;17 intt, i;18 t=cin.nextInt(); //读入测试组数

19 i=1;20 while(i<=t)21 {22 ans=cin.nextBigInteger(); //读入大数

23 b=cin.nextBigInteger();24 c=ans.add(b);25 System.out.println("Case "+i+":"); //在控制台输出结果26 //println自带换行,print不带换行

27 System.out.println(ans+" + "+b+" = "+c);28 if(i

30 i++;31 }32 }33 }34 }

用Java写的第一道题,很有纪念意义~

2013-8-11

你可能感兴趣的:(java高精度整数加减法)