zoukankan      html  css  js  c++  java
  • [LeetCode] 大数问题,相加和相乘,题 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.

    class Solution {
    public:
        string multiply(string num1, string num2) {
        }
    };

    我的解法是每次提取num2的一位,然后和num1相乘,所得结果并入string res中,这样虽然每次都要新定义一个string,效率略低,但是思路比较清晰:把字符串相乘划分成了“字符串和数字相乘” 和 “字符串相加” 两个子问题,分别解决就可以。

    处理时先将num1,和num2逆序,使得最低位在[0] 位置,这样处理起来比较方便,不易写错。

    class Solution {
    public:
        string multiply(string num1, string num2) {
            if(num1.length() == 0 || num2.length() == 0)
                return "";
            if(num1.length() == 1 && num1[0] == '0') return "0";
            if(num2.length() == 1 && num2[0] == '0') return "0";
            string res(num1.length() + num2.length(), '0');
            int i = 0, j = 0;
            reverse(num1.begin(), num1.end());
            reverse(num2.begin(), num2.end());
            for(i = 0; i < num2.length(); ++i){
                int offset = i;
                string tmp(offset + num1.length() + 1, '0');
                int add = 0;
                for(j = 0; j < num1.length(); ++j){
                    int tmpMul = (num1[j] - '0') * (num2[i] - '0') + add;
                    add = tmpMul / 10;
                    tmp[j + offset] = (tmpMul % 10) + '0';
                }
                tmp[j + offset] = add + '0';
                plus(res, tmp);
            }
            int countStartZero = 0; //高位'0'的个数
            for(i = res.length() - 1; i >= 0 && res[i] == '0'; --i, ++countStartZero);
            if(countStartZero == res.length()) return "0";
            res = res.substr(0, res.length() - countStartZero);
            reverse(res.begin(), res.end());
            return res;
        }
    private:
        void plus(string &s1, string &s2){
            int add = 0;
            for(int i = 0; i < s1.length() && (add > 0 || i < s2.length()); ++i){
                int tmp = (s1[i] - '0') + add;
                if(i < s2.length()) tmp += (s2[i] - '0');
                add = tmp / 10;
                s1[i] = (tmp % 10) + '0';
            }
        }
    };
  • 相关阅读:
    JZ初中OJ 2266. 古代人的难题
    JZ初中OJ 1341. [南海2009初中] water
    JZ初中OJ 1340. [南海2009初中] jumpcow
    JZ初中OJ 2000. [2015.8.6普及组模拟赛] Leo搭积木
    JZ初中OJ 1999.[2015.8.6普及组模拟赛] Wexley接苹果
    Unity Android平台下插件/SDK开发通用流程
    UNITY接入支付宝(未测试可行)
    Unity接入支付宝(免写安卓代码,使用JAR方式)
    Unity之多态
    unity与android交互(1)与(2)网友的整理
  • 原文地址:https://www.cnblogs.com/felixfang/p/3711078.html
Copyright © 2011-2022 走看看