leetcode -- 537. Complex Number Multiplication【字符串解析 + 复数相乘计算机实现】
2017-06-29 15:14
405 查看
题目
Given two strings representing twocomplex 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.
题意
给定两个字符串表示两个复数,返回字符串表示他们的乘积。分析及解答
【字符串处理】分割字符串,字符串转整型,字符串拼接。【运算规则】了解复数的运算规则,通过计算机实现。
public class Solution {
public String complexNumberMultiply(String a, String b) {
int realA = 0,realB = 0;
int imagineA = 0,imagineB = 0;
String arrayA[] = a.split("\\+");
String arrayB[] = b.split("\\+");
realA = Integer.parseInt(arrayA[0]);
realB = Integer.parseInt(arrayB[0]);
imagineA = Integer.parseInt(arrayA[1].substring(0, arrayA[1].indexOf('i')));
imagineB = Integer.parseInt(arrayB[1].substring(0, arrayB[1].indexOf('i')));
int newReal = realA * realB - imagineA * imagineB;
int newImagine = realA * imagineB + realB * imagineA;
StringBuilder result = new StringBuilder();
result.append(newReal).append("+").append(newImagine).append('i');
return result.toString();
}
}
相关文章推荐
- JS解析XML文件和字符串的跨浏览器实现
- 把字符串中每个字符都相同的子串解析出来--用正则表达式实现
- Multiply Strings 两个字符串代表数字相乘@LeetCode
- LeetCode—实现字符串转化为int类型的函数
- LeetCode | Multiply Strings(字符串相乘)
- 给定一个一oracle建表的sql语句,解析读出的字符串,将表名、字段名、字段类型数据取出,怎么实现啊?
- 实现可变参数函数字符串的格式简单解析样例
- android实现json数据的解析和把数据转换成json格式的字符串
- 【使用JSOUP实现网络爬虫】解析一个HTML字符串
- Oracle中通过:触发器,存储过程,Function调用实现解析Clob字段类型中存储的xml字符串
- Boost实现将字符串按格式解析到数组的功能
- 浅谈IM软件业务知识-实现富文本解析,如:解析字符串、网络链接等
- js解析xml字符串和xml文档实现原理及代码(针对ie与火狐)
- android实现json数据的解析和把数据转换成json格式的字符串
- C字符串操作函数的实现详细解析
- 源码解读:java 解析字符串为boolean四种实现方法的细节
- js解析xml字符串和xml文档实现原理及代码(针对ie与火狐)
- 利用java反射调用实现对字符串的解析,成功调入函数,并且返回值
- android实现json数据的解析和把数据转换成json格式的字符串
- Oracle中通过Function,存储过程,触发器,调用实现解析Clob字段中存在的xml字符串