• [leetcode-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.

    思路:

    首先将 ‘+’找到,将字符串分成左右两部分,然后分别转换成整数就可以了。

    int stringToint(string a,int& real,int& virtu)
        {
            int i = 0;
            for (; i < a.size();i++)//找到+号 位置i
            {
                if (a[i] == '+') break;             
            }
            
            real = atoi(a.substr(0, i).c_str());
            virtu = atoi(a.substr(i+1,a.size()-i-2).c_str());
            //cout << real << " " << virtu << endl;
        
            return 0;
        }
        string complexNumberMultiply(string a, string b)
        {
            if (a.size() == 0 || b.size() == 0) return "0";
            int real1, virtu1, real2, virtu2,real,virtu;
            stringToint(a, real1, virtu1);
            stringToint(b, real2, virtu2);
            real = real1*real2 - virtu1*virtu2;
            virtu = real1*virtu2 + virtu1*real2;
            char resu[128];
            sprintf(resu, "%d+%di", real, virtu);
            return resu;
        }
  • 相关阅读:
    Ext.js给form加背景图片
    Linux安装Scala
    idea 无法创建Scala class 选项解决办法汇总
    idea 无法创建Scala class 选项解决办法汇总
    i++和++i的区别,及其线程安全问题
    java面试题
    大数据学习——scala入门程序
    大数据学习——spark安装
    大数据学习——kafka+storm+hdfs整合
    大数据学习——日志监控告警系统
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6622109.html
Copyright © 2020-2023  润新知