leetcode【第六周】字符串数字相乘
2017-04-02 19:12
477 查看
问题描述:
Given two non-negative integers
as strings, return the product of
Note:
The length of both
< 110.
Both
only digits
Both
not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
问题分析:
如题所述,需要将两个字符串的数字进行相乘,然后结果再用字符串输出。字符串乘法能突破数据类型计算两个长值的数字相乘的限制,具有实际意义。
实现思路可以按照手写乘法的方式来实现,即使用两个数字的各位数值进行逐位相乘,保存在一个结果数组中,再对数组中各数值进行进位处理。最后根据结果数组的值输出字符串即可。
代码如下:
运行时间:
9ms
Given two non-negative integers
num1and
num2represented
as strings, return the product of
num1and
num2.
Note:
The length of both
num1and
num2is
< 110.
Both
num1and
num2contains
only digits
0-9.
Both
num1and
num2does
not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
问题分析:
如题所述,需要将两个字符串的数字进行相乘,然后结果再用字符串输出。字符串乘法能突破数据类型计算两个长值的数字相乘的限制,具有实际意义。
实现思路可以按照手写乘法的方式来实现,即使用两个数字的各位数值进行逐位相乘,保存在一个结果数组中,再对数组中各数值进行进位处理。最后根据结果数组的值输出字符串即可。
代码如下:
class Solution { public: string multiply(string num1, string num2) { int len1 = num1.length(); int len2 = num2.length(); reverse(num1.begin(),num1.end()); reverse(num2.begin(),num2.end()); int data[len1+len2]={0}; for(int i=0;i0) { index--; if(!flag&&data[index]==0)continue; else { flag = true; result += (char)(data[index]+'0'); } } if(!flag) return "0"; return result; } };
运行时间:
9ms
相关文章推荐
- [Leetcode] Multiply strings 字符串对应数字相乘
- Multiply Strings 两个字符串代表数字相乘@LeetCode
- 数字字符串两个字符串相乘
- [LeetCode]—String to Integer (atoi) 字符串转换为数字
- leetcode_38. Count and Say 统计数字个数并说出来,组成新的字符串
- 【leetcode】对撞指针应用之回文字符串判断(忽略大小写,以及出数字外其他字符)
- LeetCode 43 Multiply Strings(字符串相乘)
- 长字符串数字相乘
- LeetCode Valid Number(判断字符串是否是合法的数字表示 )
- leetcode 43 Multiply Strings (字符串相乘)
- [LeetCode]415. Add Strings(计算两个字符串表示的数字的和)
- LeetCode | Multiply Strings(字符串相乘)
- leetcode - 字符串转换成数字(String to Integer)atoi
- LeetCode-67-Add Binary(数字/字符串处理)-Easy
- LeetCode OJ String to Integer (atoi) 字符串转数字
- leetcode中字符串转化为数字
- [LeetCode] Multiply Strings 字符串相乘
- [LeetCode] Multiply Strings 字符串相乘
- leetcode_415(两个数字字符串相加,模拟大数相加)
- [LeetCode] Multiply Strings 字符串相乘