Multiply Strings
来源:互联网 发布:淘宝引流手机软件 编辑:程序博客网 时间:2024/06/06 23:54
一、问题描述
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.
二、思路
按照乘法相乘的原则,最关键的一行代码为
int temp = (v[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;这行代码中计算了当前的两位数字相乘的结果加上进位再加上上一次循环存储的值,此时的进位表示
还有最后每行计算完都要加上额外的进位,如果没有额外进位,则carry = 0;
v[i] += carry;
三、代码
class Solution {public: string multiply(string num1, string num2){ string v(num1.size() + num2.size(), '0'); for(int i = num1.size() - 1; i >= 0; --i){ int carry = 0; for(int j = num2.size() - 1; j >= 0; --j){ int temp = (v[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry; v[i + j + 1] = temp % 10 + '0'; carry = temp / 10; } v[i] += carry; } size_t start_pos = v.find_first_not_of("0"); if(string::npos != start_pos) return v.substr(start_pos); return "0"; }};
0 0
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- 接呀呀云实时语音SDK总结
- C/C++笔记--strcpy和strncpy函数的安全性分析
- ANSI的Escape序列屏幕控制码
- spring中配置quartz定时器
- TCP/IP详解
- Multiply Strings
- leetcode 100. Same Tree
- 关于在MVC中生成下拉框的各种场景应用c
- jira链接子jira单
- [Go语言]我的第三个Go语言程序
- Python篇----Requests获取网页源码(爬虫基础)
- 遇到的一些小问题
- 触控未来的日子--Day 21
- 这仅仅还是个开始