leetcode -- 537. Complex Number Multiplication【字符串解析 + 复数相乘计算机实现】

来源:互联网 发布:mysql 5.1.65.tar.gz 编辑:程序博客网 时间:2024/06/08 06:21

题目

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:

  1. The input strings will not have extra blank.
  2. 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]. Andthe 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();                    }}


原创粉丝点击