zoukankan      html  css  js  c++  java
  • LC 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.

    Runtime: 4 ms, faster than 14.90% of C++ online submissions for Complex Number Multiplication.

    class Solution {
    public:
      pair<int,int> get_ab(string s){
        int addpos = 0;
        for(int i=0; i<s.size(); i++){
          if(s[i] == '+') addpos = i;
        }
        auto p = make_pair<int,int>(0,0);
        p.first = stoi(s.substr(0,addpos));
        p.second = stoi(s.substr(addpos+1,s.size()-addpos-2));
        return p;
      }
      string complexNumberMultiply(string a, string b) {
        auto a_ab = get_ab(a);
        auto b_ab = get_ab(b);
        int x1 = a_ab.first, y1 = a_ab.second, x2 = b_ab.first, y2 = b_ab.second;
        string reta = to_string(x1*x2 - y1*y2);
        string retb = to_string(x1*y2 + x2*y1);
    
        return reta + "+" + retb + "i";
      }
    };
  • 相关阅读:
    ComboBox联动DataGridview之Access表名联动表内容
    通过进程ID获取窗口句柄(微软)
    Excel操作类
    C# TextBox自动完成
    Mdi悬浮子窗体不超过主窗体边界
    Excel导入数据库_Excel2Sql
    C#连接SQL的增删改查
    用dynamic expression运行时访问dynamic object
    添加模式匹配
    对帐脚本语言的修改
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10188363.html
Copyright © 2011-2022 走看看