LeetCode 537. Complex Number Multiplication
来源:互联网 发布:youtube 批量下载软件 编辑:程序博客网 时间:2024/05/20 06:41
题目
Given two strings representing two complex numbers.
You need to return a string representing their multiplication. Note i2 = -1 according to the definition.
Example:
Input: “1+1i”, “1+1i”
Output: “0+2i”
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.Input: “1+-1i”, “1+-1i”
Output: “0+-2i”
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
思考
题目为复数乘法,对输入的限制高(实部和虚部就算是0也要写上去;即使虚部为负数,中间的加号也要有),因此获得各个部分比较简单,只需要将string转换为int就能算出结果的实部和虚部。
答案
c++
用stringstream进行string和int的转换。
class Solution {public: string complexNumberMultiply(string a, string b) { int plusIndex1 = a.find('+'); int plusIndex2 = b.find('+'); int aReal, bReal, aImag, bImag; stringstream ss; ss << a.substr(0, plusIndex1); ss >> aReal; ss.clear(); ss << b.substr(0, plusIndex2); ss >> bReal; ss.clear(); ss << a.substr(plusIndex1 + 1, a.size() - plusIndex1 - 2); ss >> aImag; ss.clear(); ss << b.substr(plusIndex2 + 1, b.size() - plusIndex2 - 2); ss >> bImag; ss.clear(); string result1 = "", result2 = ""; int resultReal, resultImag; resultReal = aReal * bReal - aImag * bImag; resultImag = aReal * bImag + aImag * bReal; ss << resultReal; ss >> result1; ss.clear(); ss << resultImag; ss >> result2; string result = result1 + '+' + result2 + 'i'; return result; }};
阅读全文
0 0
- Leetcode-537. Complex Number Multiplication
- leetcode 537. Complex Number Multiplication
- LeetCode 537. Complex Number Multiplication
- Leetcode 537. Complex Number Multiplication
- leetcode 537. Complex Number Multiplication
- LeetCode | 537. Complex Number Multiplication
- LeetCode:537. Complex Number Multiplication
- LeetCode----537. Complex Number Multiplication
- [leetcode]537. Complex Number Multiplication
- LeetCode-537. Complex Number Multiplication
- [LeetCode]537. Complex Number Multiplication
- [leetcode]: 537. Complex Number Multiplication
- 【LeetCode】537. Complex Number Multiplication
- LeetCode 537. Complex Number Multiplication
- leetcode-complex number multiplication
- 【LeetCode】537. Complex Number Multiplication【M】
- LeetCode OJ-537.Complex Number Multiplication
- [LeetCode]537. Complex Number Multiplication<Java>
- java集合ArrayList<E>的自身嵌套
- HDU2844 Coins(多重背包)
- 【java】【开源代码分析】java并发编程与junit4
- 【java】--@PathParam 和@QueryParam
- 【计算机视觉之二】人工神经网络
- LeetCode 537. Complex Number Multiplication
- python 编写简单网页服务器
- 闭包中变量访问问题(笔试题)
- ITSM基础框架开发维护指南
- 第四第三公司小项目简单angularjs
- Linux中模拟shell实现ls命令(不加参数)
- Mysql01_基本类型与建表的sql
- C++并发编程学习——3.在线程间共享数据
- Linux 常用命令