码迷,mamicode.com
首页 > 其他好文 > 详细

Multiply Strings

时间:2015-03-31 17:37:02      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

字符串的大数乘法,模拟题

把两个字符串倒过来以后对应位置相乘,注意最终结果要去掉最前面的0

  1. class Solution {
  2. public:
  3. string multiply(string num1, string num2) {
  4. reverse(num1.begin(), num1.end());
  5. reverse(num2.begin(), num2.end());
  6. string s(num1.size() + num2.size(), ‘0‘);
  7. for (size_t i = 0; i < num1.size(); i++)
  8. {
  9. for (size_t j = 0; j < num2.size(); j++)
  10. {
  11. s[i + j] = s[i + j] - ‘0‘ + (num2[j] - ‘0‘)*(num1[i] - ‘0‘);
  12. s[i + j + 1] = s[i + j + 1] + s[i + j] / 10;
  13. s[i + j] = s[i + j] % 10 + ‘0‘;
  14. }
  15. }
  16. int notZeroIndex = s.size() - 1;
  17. while (s[notZeroIndex] == ‘0‘ && notZeroIndex>0)
  18. {
  19. notZeroIndex--;
  20. }
  21. s = s.substr(0, notZeroIndex + 1);
  22. reverse(s.begin(), s.end());
  23. return s;
  24. }
  25. };




Multiply Strings

标签:

原文地址:http://www.cnblogs.com/flyjameschen/p/4381226.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!