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.

    解题思路:

    题目本质很简单,解析输入参数稍微繁琐点。

    代码:

     1 class Solution {
     2 public:
     3     string complexNumberMultiply(string a, string b) {
     4         int num1, num2, num3, num4;
     5         int res1, res2;
     6         string sig1, sig2, res;
     7         parse(num1, num2, sig1, a);
     8         parse(num3, num4, sig2, b);
     9         res1 = num1 * num3 - num2 * num4;
    10         res2 = num1 * num4 + num2 * num3;
    11         res = to_string(res1) + "+" +to_string(res2) + "i";
    12         return res;
    13     }
    14     void parse(int& a, int& b, string& sig, const string& input) {
    15         size_t plus =  input.find("+");
    16         size_t i = input.find("i");
    17         size_t minus = input.find("-");
    18         a = stoi(input.substr(0, plus));
    19         if (minus != string::npos) {
    20             b = stoi(input.substr(plus+1, i-(plus+1)));
    21             sig = "-";
    22         } else {
    23             b = stoi(input.substr(plus+1, i-(plus+1)));
    24             sig = "+";
    25         }
    26     }
    27 };
  • 相关阅读:
    如果经常访问国外站
    CouchDB降临Android
    ubuntu server操作流程百岁版
    开源HTML解析工具包jsoup 1.3.1发布
    LEMP aka LNMP
    VC编译选项
    gae地址
    feedparser 同步博客园rss到 qq zone
    跨系统共享键盘鼠标利器分享:synergy
    支持ff,ie的回车提交
  • 原文地址:https://www.cnblogs.com/gsz-/p/9424816.html
Copyright © 2011-2022 走看看