[LeetCode]Multiply Strings
2016-04-20 11:21
405 查看
一、问题描述:
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.
Converting the input string to integer is NOT allowed.
You should NOT use internal library such as BigInteger.
二、问题分析:
题目就是模拟乘法操作,而且还是非负数,这样就比较简单了。
原本用了分治的方法去做,而且明显时间复杂度比模拟低,但竟然超时了......为了避免以后重复造轮子,这次把模拟乘法的代码贴出来。其中注释部分去掉之后为正负通用的乘法。
还有一个比较蛋疼的是命令行下to_string()总是找不到,干脆自己写一个好了(虽然这道题只是在调试的时候用了下...)
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.
Converting the input string to integer is NOT allowed.
You should NOT use internal library such as BigInteger.
二、问题分析:
题目就是模拟乘法操作,而且还是非负数,这样就比较简单了。
原本用了分治的方法去做,而且明显时间复杂度比模拟低,但竟然超时了......为了避免以后重复造轮子,这次把模拟乘法的代码贴出来。其中注释部分去掉之后为正负通用的乘法。
还有一个比较蛋疼的是命令行下to_string()总是找不到,干脆自己写一个好了(虽然这道题只是在调试的时候用了下...)
public: string multiply(string num1, string num2) { string ans(num1.length()+num2.length(), '0'); int PN = 1, n = ans.length(); if (num1.length()<1 || num2.length()<1) return ans; if (num1 == "0" || num2 == "0") return "0"; // if (num1 == "-") { // PN *= (-1); // num1 = num1.substr(1, num1.length()-1); // } // if (num2 == "-") { // PN *= (-1); // num2 = num2.substr(1, num2.length()-1); // } for (int i = num1.length()-1; i >= 0; --i, --n) { int carry = 0, pos = n-1; for (int j = num2.length()-1; j >= 0; --j, --pos) { int charMult = (num1[i]-'0')*(num2[j]-'0')+carry+ans[pos]-'0'; carry = charMult/10; ans[pos] = charMult%10+'0'; } while (carry) { int charAdd = (ans[pos]-'0')+carry; carry = charAdd/10; ans[pos--] = charAdd%10+'0'; } } int i = 0; for(; i<ans.length() && ans[i]=='0'; i++); ans = ans.substr(i, ans.length()-i); // if (PN == -1) ans = "-"+ans; return ans; } private: string to_string(int i) { stringstream ss; ss << i; string s; ss >> s; return s; }
相关文章推荐
- golang入门-- import包与包内init方法的执行时机
- oracle安装报错 /lib/i386/libawt.so:libXt.so.6:cannot open shared object file
- 一台服务器发布多个tomcat并注册服务名办法
- 算法Sedgewick第四版-第1章基础-021一双向链表,在遍历时可修改、删除元素
- Cardboard虚拟现实开发初步(二)
- PCB上 如何显示 汉字
- Java直接(堆外)内存使用详解
- 一招解决全局键盘遮挡输入框问题
- java的final关键字——修饰参数和修饰类
- 《正则表达式必知必会》-- 个人认为最好的RE入门书籍
- jQuery导入Eclipse后报错解决方法
- 如何修改android studio背景色(包括project view的背景色)保护眼睛人人有责
- String、stringbuffer与stringbuilder的区别
- Android AIDL介绍
- JavaScript DOM加载
- mysql笔记
- mockmvc 静态引入
- nginx
- 资产管理计划份额转让研究(大资管长文)
- UGUI实现的虚拟摇杆,可改变摇杆位置