Big Integer Addition
阿新 • • 發佈:2018-11-06
題目描述:
Given two non-negative integers num1
and num2
represented as string, return the sum ofnum1
and num2
.
注意事項
- The length of both num1 and num2 is < 5100.
- Both num1 and num2 contains only digits 0-9.
- Both num1 and num2 does not contain any leading zero.
- You must not use any built-in BigInteger library or convert the inputs to integer directly.
樣例
Given num1 = "123"
, num2 = "45"
return "168"
分析:
老生常談的加法題 //雖然總是記不住做法== 不能呼叫API中已有的Integer包裡的方法,所以要利用的是ALU加法器的原理:程式碼:
public String addStrings(String num1, String num2) { // 利用的是ALU加法器的原理 if(num1.equals("0")){ return num2; } if(num2.equals("0")){ return num1; } int len1 = num1.length(); int len2 = num2.length(); int len = Math.max(len1,len2); char[] result = new char[len+1]; //建立一個char陣列來儲存結果,多一位為進位 for(int k=0;k<len+1;k++){ result[k] = '0'; } int p=0, X=0, Y=0; for(int i=0; i<len+1;i++){ if(i<len1){ X = num1.charAt(len1-i-1)-'0'; }else{ X = 0; } if(i<len2){ Y = num2.charAt(len2-1-i)-'0'; }else{ Y = 0; } int temp = X + Y + p; // p是下一位的進位 result[len-i] = (char) (temp % 10 + '0'); //本位和 p = temp/10; //求進位 } int count = 0; for(;count<len+1;count++){ if(result[count]!='0'){ break; } } String res = ""; for(int i =count;i<len+1;i++){ res += result[i]; } return res; }