Leetcode 415. Add Strings 字串加法 解題報告
阿新 • • 發佈:2019-02-16
1 解題思路
就是用兩個String表示的數字,不用庫的情況下實現加法。
其實說白了就是高精度加法。。注意進位,注意處理長短不一樣的數字,都從末尾開始相加就好,不多解釋,看程式碼
2 原題
Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
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.
3 AC解
public class Solution {
public String addStrings(String num1, String num2) {
//交換最大最小的,保證後續
String longer = num1;
String shorter = num2;
if (longer.length() < shorter.length()){
longer = num2;
shorter = num1;
}
int n=longer.length();
int m=shorter.length();
char l[] = longer.toCharArray();
char s[] = shorter.toCharArray();
//餘數
int remainder = 0;
char base = '0';
//從末尾開始加
int tmp;
//從末尾開始加
StringBuilder res = new StringBuilder();
while(m --> 0){
n--;
tmp = l[n] + s[m] - 2*base + remainder;
remainder = tmp / 10;
res.append(tmp % 10);
}
//處理長的一邊
while(n--> 0){
tmp = l[n] - base + remainder;
remainder = tmp / 10;
res.append(tmp % 10);
}
//處理最後的 進位
if (remainder !=0 ) res.append(remainder);
return res.reverse().toString();
}
}