• 43. Multiply Strings 字符串表示的大数乘法


    Given two numbers represented as strings, return multiplication of the numbers as a string.

    Note: The numbers can be arbitrarily large and are non-negative.

    string multiply(string& num, char ch){
        int n = ch - '0';
        string s;
        int carry = 0;
        int x;
        for(int i=num.size()-1; i>=0; i--){
            x = (num[i]-'0') * n + carry;
            carry = x/10;
            s.insert(s.begin(), x%10+'0'); 
        }
        if (carry>0) {
            s.insert(s.begin(), carry+'0');
        }
        return s;
    }
    
    string strPlus(string& num1, string& num2) {
        string s;
        int carry=0;
        int x;
        int n1 = num1.size(); 
        int n2 = num2.size(); 
        
        int i, j;
        for(i=n1-1, j=n2-1; i>=0 || j>=0; i--, j--){
            int x1 = i>=0 ?  num1[i]-'0' : 0;
            int x2 = j>=0 ?  num2[j]-'0' : 0;
            x = x1 + x2 + carry; 
            carry = x/10;
            s.insert(s.begin(), x%10+'0');
        }
        if (carry>0) {
            s.insert(s.begin(), carry+'0');
        }
        return s;
    }
    
    string multiply(string num1, string num2) {
    
        if (num1.size()<=0 || num2.size()<=0) return "";
    
        int shift=0;
        string result="0";
        for (int i=num1.size()-1; i>=0; i--) {
            string s = multiply(num2, num1[i]);        
            for(int j=0; j<shift; j++){
                s.insert(s.end(), '0');
            }
            result = strPlus(result, s);
            shift++;
        }
        //check if it is zero
        if (result[0]=='0') return "0";
        return result;
    }
  • 相关阅读:
    Nodejs 开发指南 Nodejs+Express+ejs 开发microblog开发心得
    转载 java学习注意点
    STM32f103的数电采集电路的ADC多通道采集程序
    时间复杂度与空间复杂度
    RS232串口通信详解
    实现扫码登录
    TCP/UDP区别与联系
    Tcp三次握手/四次挥手
    浅谈CSRF攻击方式
    图片淡入淡出
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5246792.html
Copyright © 2020-2023  润新知