zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    hover动画
    杀毒软件性能比较
    python文件转exe
    react 踩的坑
    js前端模块化(一) commonjs
    iframe嵌套页面 音频在微信公众号环境无法播放
    js正则表达式
    js修改伪类元素样式
    OAF 开发 Q&A
    JS打开窗口问题
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5246792.html
Copyright © 2011-2022 走看看