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";
      }
    };
  • 相关阅读:
    View.VISIBLE、INVISIBLE、GONE的区别
    Android中TextView内容过长加省略号
    Android 读取SIM卡参数
    java分布式通信系统(J2EE分布式服务器架构)
    Java分布式处理技术(RMI,JDNI)
    Java分布式缓存框架
    spring
    Apache与Nginx的优缺点比较
    Java如何获取文件编码格式
    java 乱码问题-Dfile.encoding=UTF-8
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10188363.html
Copyright © 2011-2022 走看看