zoukankan      html  css  js  c++  java
  • LeetCode OJ--Multiply Strings **

    https://oj.leetcode.com/problems/multiply-strings/

    用字符串实现大数乘法,细节题,细节很多

     
    class Solution {
    public:
        string multiply(string num1, string num2) {
            if(num1.empty() || num1.size() == 0 || num2.empty() || num2.size() == 0)
                return "";
            //0
            if(num1 == "0" || num2 == "0")
                return "0";
            
            //keep num2 the smaller
            if(num1.size() < num2.size())
            {
                //exchange
                string t = num1; num1 = num2; num2 = t;
            }
            string ans = "";
            ans.resize(num1.size());
            
            //initialize
            for(size_t i = 0; i < num1.size(); i++)
                ans[i] = '0';
                
            int pos = 0;
            int times = 0;
            int sum = 0;
            
            for(int index2 = num2.size() - 1; index2 >= 0; index2--)
            {
                pos = ans.size() - 1 - times;
                times++;
                int carry = 0;
                for(int index1 = num1.size() - 1; index1 >=0; index1--)
                {
                    sum = carry + (num1[index1] - '0')*(num2[index2] - '0') + ans[pos] - '0';
                    carry = sum/10;
                    ans[pos] = sum%10 + '0';
                    pos--;
                    // ans has been the beginning while index1 not, and ans has been the beginning and here are carry
                    if(pos == -1 &&(carry > 0|| index1 != 0))
                    {
                        string t = "0";
                        t[0] = carry + '0';
                        ans = t + ans;
                        carry = 0;
                        pos = 0;
                    }
                }
            }
            return ans;
        }
    };
  • 相关阅读:
    窗口设置背景图片
    双链表
    单链表
    Hough直线检测
    轮廓跟踪
    轮廓提取
    基于腐蚀的二值图像距离变换
    创建对话框用于交互
    hello world
    c#---params参数
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3876266.html
Copyright © 2011-2022 走看看