LeetCode算法题之Multiply Strings
来源:互联网 发布:网络赌球有赢钱的吗 编辑:程序博客网 时间:2024/06/05 03:57
问题描述:
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.
一个数字以字符串的形式相乘,这就意味着传统的乘法肯定不能满足,计算机表示不了那么大的数字
解题思路:
模拟乘法的竖式运算,具体过程见代码注释,我这写的太臃肿了,大神们都是四五十行搞定,这也导致我耗时很长,144ms勉强AC吧。
class Solution{public: string multiply(string num1, string num2) { string result; map<int, int> numMap1; map<int, int> numMap2; map<int, int> numMap3; //特殊情况 if (("0" == num1) || ("0" == num2)) { return "0"; } //将每一位上的数字字符当做科学计数法来表示a*pow(10,b), //如123中的2,记为2*pow(10,1),用map存放2和指数1 int base1,exponent1; exponent1 = num1.length()-1; for(unsigned int i=0; i<num1.length(); i++) { base1 = num1[i]-'0'; numMap1[exponent1--] = base1; } int base2,exponent2; exponent2 = num2.length()-1; for(unsigned int i=0; i<num2.length(); i++) { base2 = num2[i]-'0'; numMap2[exponent2--] = base2; } //模拟乘法的手算方式,但此处我只是计算,该进位的并没有进位 for( map<int, int>::iterator iter1 = numMap1.begin(); iter1 != numMap1.end(); iter1++) { for( map<int, int>::iterator iter2 = numMap2.begin(); iter2 != numMap2.end(); iter2++) { int key; key = iter1->first + iter2->first; numMap3[key] += iter1->second * iter2->second; } } //完成进位,需要多次反复计算,直到所有的a都是个位数 for( map<int, int>::iterator iter3 = numMap3.begin(); iter3 != numMap3.end(); iter3++) { int key = iter3->first; int value = iter3->second; if(value > 9) { numMap3[key] = value % 10; while(true) { value = value / 10; key++; numMap3[key] += value % 10; if(value == 0) break; } } } //本来可以输出结果了,到这儿一看结果是反的 for( map<int, int>::iterator iter3 = numMap3.begin(); iter3 != numMap3.end(); iter3++) { result += iter3->second + '0'; } char temp; //没办法,字符串逆序 for(size_t i=0; i<result.length()/2; i++) { temp=result[i]; result[i]=result[result.length()-i-1]; result[result.length()-i-1]=temp; } //这个逆序之后第一个数字可能是0,得去掉,原因嘛,好好琢磨 if(result[0] == '0') result = result.substr(1,result.length()-1); return result; }};
0 0
- LeetCode算法题之Multiply Strings
- Leetcode之Multiply Strings
- LeetCode之Multiply Strings
- 【Leetcode】之Multiply Strings
- LeetCode 之 Multiply Strings
- LeetCode 43题之 Multiply Strings
- leetcode:Multiply Strings(字符串的乘法)【面试算法题】
- LeetCode OJ算法题(四十二):Multiply Strings
- 【LeetCode】43. Multiply Strings 大数相乘算法
- Leetcode学习之Multiply Strings (43)
- LeetCode进阶之路( Multiply Strings)
- 每日算法之三十四:Multiply Strings
- LeetCode: Multiply Strings
- LeetCode Multiply Strings
- LeetCode: Multiply Strings
- [Leetcode] Multiply Strings
- [LeetCode] Multiply Strings
- [Leetcode] Multiply Strings
- SICP第一章学习笔记
- 今日的精彩关于IDE XCODE6(2015331)
- JS-Cookie操作
- HDU 4642 - Fliping game(博弈)
- 面试之-jvm
- LeetCode算法题之Multiply Strings
- 人生短暂
- poj 2115 C Looooops(解二元一次不定方程)
- LightOJ 1341 - Aladdin and the Flying Carpet(算术基本定理 唯一分解定理)
- TCP协议疑难杂症全景解析
- Struts2 + Spring + Hibernate 入门 2
- 第四周项目2 分数的雏形
- 使用Junit进行单元测试
- Ubuntu下的一些命令_2