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";
    }
  • 相关阅读:
    VOA 转
    DataTable中动态的赋值 转
    哈希表 转
    利用Hook技术实现键盘监控 转
    sql 里的 order by 和 group by 的区别 转
    DES加密算法 转
    Windows的消息机制 转
    “赢在中国”点评人给80后年轻人的30个忠告 转
    ASCII码对照表 转
    以太网 转
  • 原文地址:https://www.cnblogs.com/luojunc/p/6668739.html
Copyright © 2011-2022 走看看