Java使用LinkedList实现大数相加

来源:互联网 发布:淘宝评价100字范文 编辑:程序博客网 时间:2024/06/08 06:25
   Java.math中有实现大数操作的BigInteger类和BigDecimal类,分别进行整数的大数操作和小数的大数操作。但是下面的程序是用LinkedList实现了大数操作,LinkedList作为List的实现类,链表的数据结构。相比ArrayList,它有着增加修改速度快的优势。代码如下:

public class Test{public static void main(String[] args) {// TODO Auto-generated method stubList<Integer> bigNumber = new LinkedList<>();for(int i = 0; i <30; i++) {bigNumber.add(7);}List<Integer> bigNumber1 = new LinkedList<>();for(int i = 0; i < 30; i++) {bigNumber1.add(6);}System.out.println("bigNumber:"+bigNumber.toString());System.out.println("bigNumber1:"+bigNumber1);//Test.addMethod(bigNumber1, bigNumber1);List<Integer>m = Test.addMethod(bigNumber, bigNumber1);for(int i =m.size() - 1; i >= 0 ; i--) {System.out.print(m.get(i));//顺序放进去,倒序输出}}public static List<Integer> addMethod(List<Integer> a, List<Integer> b) {List<Integer> sum = new LinkedList<>();int carry = 0; //存储十位上的数for(int i = 0; i < 30; i++) {//sum.add(a.get(i) + b.get(i));int temp ; //存取元素相加的值if (carry > 0) {temp = a.get(i) + b.get(i) + carry; //当有十位数时就要加上carry = 0;}else {temp = a.get(i) + b.get(i);}if(temp >= 10) {int u = temp%10;//存取个位int y = temp/10; //存取十位sum.add(u);carry = y;if (i == 29) {//当加到最后一位时,应该把十位也放到结果里sum.add(carry);}}else {sum.add(temp);}}return sum;}}

0 0
原创粉丝点击