1. 程式人生 > >LC-415 字串相加(大數相加)

LC-415 字串相加(大數相加)

目標:

輸入兩個十進位制數的字串,輸出它們的和

 

思路:

這道題有兩個思路,一個是最容易想到的,就是類小學加法,一位一位的加,記錄是否要進位,一位一位地輸出結果。

而我的思路是利用字串分割,將比較大的數字加法,分成每8位的相加,這裡就要處理好分割計算後,進位的處理,以及字串是否需要補零的操作(因為有可能8位中前幾位是0,使得加出來的數值再變回字串時位數不足8)。

最終這種分割方法可以做到12ms通過測試。

 

程式碼:

 1 class Solution {
 2 public:
 3     string addStrings(string num1, string
num2) { 4 // make the longer number become num1 5 if (num2.length() > num1.length()) { 6 string temp = num1; 7 num1 = num2; 8 num2 = temp; 9 } 10 string answer; 11 bool flag = false; // flag as a carry signal 12 //
judge if it is a large num that over an int range 13 if (num2.length() > 8) { 14 // split the num in 8 bits each group then do the sum 15 for (int i = num2.length(), j = num1.length(); i > 0; i -= 8, j -= 8) { 16 int len = 8; 17 // if there are no more can split
18 if (i < 8) 19 len = i; 20 string sub2 = num2.substr(i - len, len); 21 string sub1 = num1.substr(j - len, len); 22 int n2 = stoi(sub2); 23 int n1 = stoi(sub1); 24 int sum = n1 + n2; 25 // check carry 26 if (flag) 27 sum++; 28 string num = to_string(sum); 29 // check if sum is over range, need a carry signal 30 if (sum >= pow(10, len)) { 31 flag = true; 32 num.erase(0, 1); 33 } 34 else 35 flag = false; 36 // make complement of lack of 0 37 num.insert(0, len - num.length(), '0'); 38 // append the number 39 answer.insert(0, num); 40 } 41 } 42 else { 43 // no need to split 44 int len = num2.length(); 45 string sub1 = num1.substr(num1.length() - len, len); 46 int n2 = stoi(num2); 47 int n1 = stoi(sub1); 48 int sum = n1 + n2; 49 string num = to_string(sum); 50 // check if sum is over range, need a carry signal 51 if (sum >= pow(10, len)) { 52 flag = true; 53 num.erase(0, 1); 54 } 55 answer = num; 56 } 57 // deal to the rest of longer number1 58 string prefix = num1.substr(0, num1.length() - num2.length()); 59 if (flag) { 60 int i = prefix.length() - 1; 61 char new_digit = 0, digit; 62 while ((new_digit == '0' || new_digit == 0) && i >= 0) { 63 digit = prefix[i]; 64 new_digit = ((digit - '0' + 1) % 10) + '0'; 65 prefix[i] = new_digit; 66 i--; 67 } 68 if (i == -1 && (new_digit == '0' || new_digit == 0)) { 69 prefix.insert(0, 1, '1'); 70 } 71 } 72 return prefix + answer; 73 } 74 };