大数相加 java
import java.util.*;public class myJava { public static void main(String[] ags) { Scanner console = new Scanner(System.in); String str1, str2; str1 = console.nextLine(); str2 = console.nextLine(); bigNumber num1 = new bigNumber(str1); bigNumber num2 = new bigNumber(str2); num1.add(num2).print(); }}class bigNumber { bigNumber(int str[]) { int len = str.length; int i, j; for (i = 0; str[i] == 0 && i < len; ++i)//去前缀0 ; if( i == len )//当为0的时候的处理,但不知道为什么好像没起到应有的作用 { this.num = new int[1]; this.num[0] = 0; } else this.num = new int[len - i]; for (j = 0; i < len; ++i, ++j) { this.num[j] = str[i]; } } bigNumber(String str) { int len = str.length(); int i, j; for (i = 0; str.codePointAt(i) == '0' && i < len; ++i)//去前缀0 ; if( i == len )//当为0的时候的处理,但不知道为什么好像没起到应有的作用 { this.num = new int[1]; this.num[0] = 0; } else this.num = new int[len - i]; for (j = 0; i < len; ++i, ++j) { num[j] = str.codePointAt(i) - '0'; } } public bigNumber add(bigNumber num2) { int len1 = this.num.length; int len2 = num2.num.length; int mostLen = (len1 > len2) ? len1 : len2; int[] sum = new int[mostLen + 1]; int temp; for (temp = 0, --len1, --len2; len1 >= 0 && len2 >= 0; --len1, --len2, --mostLen) {//从个位开始相加 sum[mostLen] = (this.num[len1] + num2.num[len2] + temp) % 10; temp = (this.num[len1] + num2.num[len2] + temp) / 10; } for (; len1 >= 0; --len1, --mostLen) {//num中剩余部分 sum[mostLen] = (this.num[len1] + temp) % 10; temp = (this.num[len1] + temp) / 10; } for (; len2 >= 0; --len2, --mostLen) {//num2.num中的剩余部分 sum[mostLen] = (num2.num[len2] + temp) % 10; temp = (num2.num[len2] + temp) / 10; } sum[0] = temp; bigNumber num3 = new bigNumber(sum); return num3; } public void print() { int len = num.length; for (int i = 0; i < len; ++i) System.out.print(num[i]); } int[] num;}
功能:输入两个很大的正整数并相加;
但不知道为什么输入0的时候会出错啊唉。。
哪里不对的,就请狠狠的批吧Orz
TAG:大数相加 java 手写