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";
    }
  • 相关阅读:
    初级算法-1.从排序数组中删除重复项
    一个字符串匹配函数...
    Working With JSON
    javascript iterator
    js 正则表达式验证密码、邮箱格式.....
    SpringMVC 定时任务
    JS 数组去重
    JAVA 跨域请求 不用JSONP 不用CORS
    openLayer 跳到指定坐标
    清空CheckBox 勾选
  • 原文地址:https://www.cnblogs.com/luojunc/p/6668739.html
Copyright © 2011-2022 走看看