zoukankan      html  css  js  c++  java
  • leetcode: Multiply Strings

    http://oj.leetcode.com/problems/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搞定。

    class Solution {
    public:
        string multiply(string num1, string num2) {
            reverse(num1.begin(), num1.end());
            reverse(num2.begin(), num2.end());
            
            if (("0" == num1) || ("0" == num2)) {
                return "0";
            }
            
            string result = "";
            int i, j;
            int flag = 0, steps = 0;
            
            for (int i = 0; i < num1.length(); ++i) {
                int position = steps;
                
                for (int j = 0; j < num2.length(); ++j) {
                    int v = (num1[i] - '0') * (num2[j] - '0') + flag;
    
                    if (position < result.length()) {
                        v += result[position] - '0';
                        result[position] = (v % 10) + '0';
                    }
                    else {
                        result.append(1, (v % 10) + '0');
                    }
                    
                    flag = v / 10;
                    ++position;
                }
                
                if (flag > 0) {
                    result.append(1, flag + '0');
                }
                
                flag = 0;
                ++steps;
            }
            
            reverse(result.begin(), result.end());
            
            return result;
        }
    };
  • 相关阅读:
    mvc实例
    mvc
    设计模式总结
    作业——《XXX》系统设计时所实现的质量属性战术
    实训第十四天
    实训第十三天
    实训第十二天
    实训第十一天
    实训第十天
    实训第九天
  • 原文地址:https://www.cnblogs.com/panda_lin/p/multiply_strings.html
Copyright © 2011-2022 走看看