zoukankan      html  css  js  c++  java
  • 537. Complex Number Multiplication

    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]. And the output should be also in this form.

    My Solution:

    According to the multiplication rule of Complex Number, (a+bi)*(c+di)=(ac-bd)+(bc+ad)i, so:

    public class Solution {
        public String complexNumberMultiply(String a, String b) {
            int num1,num2,num3,num4;
            num1 = Integer.parseInt(a.split("\+")[0]);
            num2 = Integer.parseInt(a.split("\+")[1].split("i")[0]);
            num3 = Integer.parseInt(b.split("\+")[0]);
            num4 = Integer.parseInt(b.split("\+")[1].split("i")[0]);
            
            int pre = num1*num3 - num2*num4;
            int aft = num2*num3 + num1*num4;
            
            return pre + "+" + aft + "i"; 
        }
    }

    Other's Solution:

    public String complexNumberMultiply(String a, String b) {
        int[] coefs1 = Stream.of(a.split("\+|i")).mapToInt(Integer::parseInt).toArray(), 
              coefs2 = Stream.of(b.split("\+|i")).mapToInt(Integer::parseInt).toArray();
        return (coefs1[0]*coefs2[0] - coefs1[1]*coefs2[1]) + "+" + (coefs1[0]*coefs2[1] + coefs1[1]*coefs2[0]) + "i";
    }
  • 相关阅读:
    解决response在controller返回乱码的解决方式
    Injection of autowired dependencies failed;错误解决
    sql mybatis 使用concat乱码
    【算法基础】欧几里得gcd求最大公约数
    sql视图和表的区别
    在idea下创建maven
    Arrays.sort()自定义排序
    数组
    java 遍历数组
    抽象与接口
  • 原文地址:https://www.cnblogs.com/luojunc/p/6668739.html
Copyright © 2011-2022 走看看