美文网首页
[刷题防痴呆] 0537 - 复数乘法 (Complex Num

[刷题防痴呆] 0537 - 复数乘法 (Complex Num

作者: 西出玉门东望长安 | 来源:发表于2021-10-14 00:29 被阅读0次

    题目地址

    https://leetcode.com/problems/complex-number-multiplication/

    题目描述

    537. Complex Number Multiplication
    
    A complex number can be represented as a string on the form "real+imaginaryi" where:
    
    real is the real part and is an integer in the range [-100, 100].
    imaginary is the imaginary part and is an integer in the range [-100, 100].
    i2 == -1.
    Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.
    
     
    
    Example 1:
    
    Input: num1 = "1+1i", num2 = "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: num1 = "1+-1i", num2 = "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.
    
    
    
    
    

    思路

    • stringbuffer.
    • 以加号为界split num1和num2, 然后去掉末尾的i, 得到a, b, c, d四个数字值.
    • 数学法计算, (a * c - b * d) + (b * c + a * d)i即为答案.

    关键点

    • 注意, 加号为特殊字符, split需要用split("\+").
    • 注意, substring的用法.

    代码

    • 语言支持:Java
    class Solution {
        public String complexNumberMultiply(String num1, String num2) {
            String[] strs1 = num1.split("\\+");
            String[] strs2 = num2.split("\\+");
    
            int a = Integer.parseInt(strs1[0]);
            int b = Integer.parseInt(strs1[1].substring(0, strs1[1].length() - 1));
            int c = Integer.parseInt(strs2[0]);
            int d = Integer.parseInt(strs2[1].substring(0, strs2[1].length() - 1));
    
            StringBuffer sb = new StringBuffer();
            sb.append(a * c - b * d);
            sb.append("+");
            sb.append(b * c + a * d);
            sb.append("i");
    
            return sb.toString();
        }
    }
    

    相关文章

      网友评论

          本文标题:[刷题防痴呆] 0537 - 复数乘法 (Complex Num

          本文链接:https://www.haomeiwen.com/subject/hoysoltx.html