LeetCode OJ:Multiply Strings (字串乘法)

來源:互聯網
上載者:User

標籤:

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

 

給出兩個字串,返回對應數字想乘後的字串,由於這個字串可能很大,所以不能採用一般的乘法,這裡用的方法是類比手工的乘法運算,演算法

本身很簡單,就是當時寫的時候有些很小的細節搞錯了,找了很久的錯。啊啊啊啊啊,要細心啊。大媽如下,沒什麼好說的:

 1 class Solution { 2 public: 3     string multiply(string num1, string num2) { 4         if(num1 == "0" || num2 == "0") return "0"; 5         int steps = 0; 6         int pos = 0; 7         int flag = 0; 8         int val = 0; 9         string result = "";10         reverse(num1.begin(), num1.end());11         reverse(num2.begin(), num2.end());12         int len1 = num1.length();13         int len2 = num2.length();14         for(int i = 0; i < len1; ++i){15               pos = steps;16             for(int j = 0; j < len2; ++j){17                 val = (num1[i] - ‘0‘)*(num2[j] - ‘0‘) + flag;18                 if(result.size() <= pos){19                     result.append(1, val%10 + ‘0‘);20                 }else{21                     val += (result[pos] - ‘0‘);22                     result[pos] = val%10 + ‘0‘;23                 }24                 flag = val/10;25                 pos++;  26             }27             if(flag > 0)28                 result.append(1, flag + ‘0‘);29             flag = 0;30             steps++;31         }32         reverse(result.begin(), result.end());33         return result;34     }35 };

 

LeetCode OJ:Multiply Strings (字串乘法)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.