标签:char java scanner generated 统一 ret rate array 大数乘法
大数加法相比大数乘法来说就相对简单了,仍可以利用手工模拟加法的思想来计算大数加法,大数加法也可以采用先进行加法计算,即第i位的数相加仍保存在第i位,最后再统一处理进位。由于大数加法比较简单就边加边处理进位。
1 import java.util.Scanner; 2 3 public class bigNumberPlus { 4 static char[] reverse(char[] ch){//字符反转,即123转为321 5 int length = ch.length; 6 char[] temp = new char[length]; 7 for(int i=0;i<length;i++){ 8 temp[length-1-i] = ch[i]; 9 } 10 11 12 return temp; 13 } 14 static void plus(char[] chr1, char[] chr2){ 15 int length = chr1.length>=chr2.length?chr1.length:chr2.length; 16 chr1 = reverse(chr1); 17 chr2 = reverse(chr2); 18 int [] result = new int [length]; 19 20 int gobit = 0; 21 for(int i=0;i<length;i++){ //如果一个数的位数已遍历完,剩下的位数由0代替 22 int a_number = i<chr1.length?(chr1[i]-48):0; 23 int b_number = i<chr2.length?(chr2[i]-48):0; 24 int temp = gobit + a_number+b_number; 25 if(temp>=10){ 26 result[i] = temp-10; 27 gobit = 1; 28 }else{ 29 result[i] = temp; 30 gobit = 0; 31 } 32 } 33 if(gobit>0) //最高位进位的话就输出,没将进位保存在result数组中 34 System.out.print(gobit); 35 for(int i=length-1;i>=0;i--) 36 System.out.print(result[i]); 37 } 38 public static void main(String[] args) { 39 // TODO Auto-generated method stub 40 Scanner sc = new Scanner(System.in); 41 char [] chr1 = sc.next().toCharArray(); 42 char [] chr2 = sc.next().toCharArray(); 43 plus(chr1, chr2); 44 45 } 46 47 }
标签:char java scanner generated 统一 ret rate array 大数乘法
原文地址:http://www.cnblogs.com/skylv/p/7274543.html