• LeetCode Complex Number Multiplication


    原题链接在这里:https://leetcode.com/problems/complex-number-multiplication/description/

    题目:

    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.

    题解:

    (aReal + aImag*i)*(bReal + bImag*i) = (aReal*bReal- aImag*bImag) + (aReal*bImag+bReal*aImag)*i.

    从原有string里提取出实数和虚数两部分组成答案.

    Time Complexity: O(a.length() + b.length()). split用时

    Space: O(a.length() + b.length()). 中间的string arr.

    AC Java:

     1 class Solution {
     2     public String complexNumberMultiply(String a, String b) {
     3         String [] aArr = a.split("\+|i");
     4         String [] bArr = b.split("\+|i");
     5         int aReal = Integer.valueOf(aArr[0]);
     6         int aImag = Integer.valueOf(aArr[1]);
     7         int bReal = Integer.valueOf(bArr[0]);
     8         int bImag = Integer.valueOf(bArr[1]);
     9         return (aReal*bReal-aImag*bImag) + "+" + (aReal*bImag+aImag*bReal) + "i";
    10     }
    11 }

      

  • 相关阅读:
    旅行计划
    两只塔姆沃斯牛
    迷宫
    异或序列
    异或之和
    素数个数
    SAC E#1
    [JSOI2010]Group 部落划分 Group
    [USACO12FEB]附近的牛Nearby Cows
    [HNOI2008]Cards
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7723113.html
Copyright © 2020-2023  润新知