Multiply Strings [LeetCode]

Problem Description http://oj.leetcode.com/problems/multiply-strings/

Basic idea is to multiply two nums like we do caculation on paper, one by one digital multiplication, then add the temporary results together to get the final one. Be careful about the last carry digital.

 1 class Solution {

 2 public:

 3     string multiply_one_digital(char c, string num2, int tail){

 4         string result;

 5         for(int i = 0; i < tail; i ++) {

 6             result.push_back('0');

 7         }

 8         

 9         int carry = 0;

10         for(int i = num2.size() - 1; i >= 0; i-- ) {

11             int one_result = (c - 48) * (num2[i] - 48) + carry;

12             carry = one_result/10;

13             char current_digital = one_result % 10 + 48;

14             result.insert(result.begin(),current_digital);

15         }

16         

17         if(carry > 0)

18             result.insert(result.begin(), (char)(carry + 48));

19         

20         return result;

21     }

22     

23     string multiply(string num1, string num2) {

24         // Note: The Solution object is instantiated only once and is reused by each test case.

25         string result;

26         if(num1.size() == 0 || num2.size() == 0)

27             return result;

28         if((num1.size() == 1 && num1[0] == '0') ||

29             (num2.size() == 1 && num2[0] == '0')) {

30             result.push_back('0');

31             return result;

32         }

33         

34         vector<string> tmp_results;

35         for(int i = num1.size() - 1; i >= 0; i -- ) {

36             if(num1[i] == '0')

37                 continue;

38             

39             tmp_results.push_back(multiply_one_digital(num1[i], num2, num1.size() - 1 - i));

40         }

41         

42         //add all temporary results

43         string last_tmp_result = tmp_results[tmp_results.size() - 1];

44         int carry = 0;

45         for(int i = 0; i < last_tmp_result.size(); i ++ ){

46             int one_result = 0;

47             for( auto item: tmp_results) {

48                 if(i > item.size() - 1)

49                     continue;

50     

51                 one_result += (item[item.size() -1 - i] - 48);

52             }

53     

54             one_result += carry;

55             carry = one_result/10;

56             char current_digital = one_result % 10 + 48;

57             result.insert(result.begin(),current_digital); 

58         }

59         

60         if(carry > 0)

61             result.insert(result.begin(), (char)(carry + 48));

62         

63         return result;

64     }

65 };

 

你可能感兴趣的:(LeetCode)