43. Multiply Strings
2015-11-02 15:45
274 查看
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.
思路:
利用竖式的思想,进行乘法运算。
3 4
* 1 3
——————
9 12
3 4
——————
3 13 12
再处理进位:
3 13 12 - > 3 14 2 -> 4 4 2
Note: The numbers can be arbitrarily large and are non-negative.
思路:
利用竖式的思想,进行乘法运算。
3 4
* 1 3
——————
9 12
3 4
——————
3 13 12
再处理进位:
3 13 12 - > 3 14 2 -> 4 4 2
class Solution { public: string multiply(string num1, string num2) { reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); int carry = 0; string result; int len1 = num1.length(); int len2 = num2.length(); int resLen = len1+len2-1; for(int resPos = 0; resPos<resLen;++resPos) //indicate the pos of the result { int sum = 0; for(int i = max(0,resPos-len2+1); i < len1; ++i) //traverse the digit of num1 { int j = resPos-i; //indicate the pos of num2 if(j < 0) break; sum += (num1[i]-'0')*(num2[j]-'0'); } sum += carry; result.push_back(sum % 10+'0'); carry = sum/10; } while(carry > 0) { result.push_back(carry % 10+'0'); carry /= 10; } reverse(result.begin(), result.end()); if(result.find_first_not_of('0') == string::npos) return "0";//排除全0的情况 else return result; } };
相关文章推荐
- selenium IDE 定时执行case及log保存的方法
- linux基础 --- shell
- ArcMap无法创建新样式,或将符号添加到样式
- python字符编码错误的解决方案
- cocosjs显示跨域图片的办法
- jQuery Mobile移动网站开发
- html标签
- Java对象初始化详解
- OpenGL ES之glUniform函数
- 4.6 总结
- memcached简介及java使用方法
- 导航菜单
- W3C标准
- Mac&iOS Socket
- jenkins定时构建
- Modsecurity(开源waf)深度使用
- HashMap的存储结构
- 互联网医疗不是救命稻草
- Android 高仿微信 获取最近刚刚拍照的缩略图 功能实现
- SpringMVC上传文件