537. Complex Number Multiplication(C++)
来源:互联网 发布:易建联cba数据 编辑:程序博客网 时间:2024/06/06 14:09
原題
Given two strings representing two complex numbers.
You need to return a string representing their multiplication. Note i2 = -1 according to the definition.
Example 1:
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.
Example 2:
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.
Note:
- The input strings will not have extra blank.
- The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form.
解題思路
使用+和i劃分複數數字區域,把字符串轉為數字,進行運算
代碼
#include <sstream>
#include <stdlib.h>
using namespace std;
class Solution {
public:
string complexNumberMultiply(string a, string b) {
int A, B, C, D, E, F;
string result = "";
A = atoi(a.substr(0,a.find('+')).c_str());
B = atoi(a.substr(a.find('+')+1,a.find('i')).c_str());
C = atoi(b.substr(0,b.find('+')).c_str());
D = atoi(b.substr(b.find('+')+1,b.find('i')).c_str());
E = (A*C - B*D);
F = (A*D + B*C);
stringstream ss1, ss2;
string E_str, F_str;
ss1 << E;
ss1 >> E_str;
ss2 << F;
ss2 >> F_str;
result += E_str;
result += "+";
result += F_str;
result += "i";
return result;
}
};
感想
想着考試拿C++去做,所以還是換回用C++寫好了。streamstring不知道為甚麼不能用兩次,轉換要使用不同的ss才可以,我不知道這個卡了我一些時間……
- 537. Complex Number Multiplication(C++)
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- 537.Complex Number Multiplication
- Leetcode-537. Complex Number Multiplication
- leetcode 537. Complex Number Multiplication
- 如何分离MP4、FLV等格式视频为H264码流
- 【Scikit-Learn 中文文档】无监督降维
- UGUI screen auto adaptation by code
- [LeetCode] Minimum Path Sum
- Android入门 —— activity的启动流程源码阅读
- 537. Complex Number Multiplication(C++)
- 设计推荐系统的10条经验与教训
- 安装cocoapods遇到YAML safe loading is not available. Please upgrade psych to a version that supports saf
- Java内省技术
- emacs 打开有中文内容的文件会卡的解决方案
- CSS-外边框与内边框属性
- jdk1.8.0_131卸载装上jdk1.8.0_151,更改项目的java版本后eclipse报Project facet Java 1.8 is not supported by target r
- 【配置】sqlyog远程连接mysql数据库
- js操作符类型转换大全(前端面试题之操作符)