zoukankan      html  css  js  c++  java
  • 43. Multiply Strings

    Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

    Note:

    1. The length of both num1 and num2 is < 110.
    2. Both num1 and num2 contains only digits 0-9.
    3. Both num1 and num2 does not contain any leading zero.
    4. You must not use any built-in BigInteger library or convert the inputs to integer directly

    常规计算,一个被乘数,一个乘数

    class Solution {
    public:
        string multiply(string num1, string num2) {
            string sum(num1.size() + num2.size(), '0');   //积的长度初始化为两个数的长度之和
            for (int i = num1.size() - 1; 0 <= i; --i) {
                int carry = 0;
                for (int j = num2.size() - 1; 0 <= j; --j) {
                    int tmp = (sum[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;
                    sum[i + j + 1] = tmp % 10 + '0';    
                    carry = tmp / 10;                     //进位值计算
                }
                sum[i] += carry;                           //进位*************注意此处进位进到了被乘数上边
            }
            size_t startpos = sum.find_first_not_of("0");  //找到不是零的开头,即积的有效位的开始。
            if (string::npos != startpos) {                //npos是一个常数,用来表示不存在的位置,
                return sum.substr(startpos);               //截取有效位 
            } 
            return "0";
        }
    };
  • 相关阅读:
    java入门学习(二)
    java入门学习(一)
    python3之数据类型
    pip基础用法
    python中的序列化与反序列化
    python装饰器
    python WEB接口自动化测试之requests库详解
    QQ发送邮件实例
    获取当前目录下最新的文件
    The Zen of Python
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7881282.html
Copyright © 2011-2022 走看看