zoukankan      html  css  js  c++  java
  • LeetCode 043 Multiply Strings

    题目要求: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.

    分析:

    参考网址:http://blog.csdn.net/pickless/article/details/9235907

    利用竖式的思想,进行乘法运算。

            3    4

    *      1    3

    ——————

           9      12

    3     4

    ——————

    3     13     12

    再处理进位:

    3 13 12 - > 3 14 2 -> 4 4 2

    代码如下:

    class Solution {
    public:
        string multiply(string num1, string num2) {
    
            int flag = 1;
            
            //先处理符号
            if (num1[0] == '-' || num2[0] == '-') {
                if (num1[0] == '-') {
                    flag *= -1;
                    num1 = num1.substr(1, num1.size() - 1);
                }
                if (num2[0] == '-') {
                    flag *= -1;
                    num2 = num2.substr(1, num2.size() - 1);
                }
            }
            
            int length = num1.size() + num2.size() + 1;
            int s[length];
            
            memset(s, 0, sizeof(int) * length);
            
            int i = 0, temp = 0;
            
            for (i = 0; i < num1.size(); i++) {
                for (int j = 0; j < num2.size(); j++) {
                    s[(num1.size() - i - 1) + (num2.size() - j - 1)] += (num1[i] - '0') * (num2[j] - '0');
                }
            }
            
            //进位
            for (i = 0; i < length; i++) {
                s[i + 1] += s[i] / 10;
                s[i] = s[i] % 10;
            }
            
            for (i = 0; i < length / 2; i++) {
                temp = s[i];
                s[i] = s[length - i - 1];
                s[length - i - 1] = temp;
            }
            
            string ans = flag < 0 ? "-" : "";
            for (i = 0, temp = -1; i < length; i++) {
                if (s[i] != 0) {
                    temp = 1;
                }
                if (temp > 0) {
                    ans += s[i] + '0';
                }
            }
            return ans == "" ? "0" : ans;
        }
    };
  • 相关阅读:
    Hibernate缓存机制
    如何建立索引
    数据库索引及基本优化入门
    索引优化-2
    索引优化-1
    Linux基本命令参数
    Spring 依赖注入(控制反转)介绍
    Linux的软连接和硬连接
    聚簇索引(Clustered Index)和非聚簇索引 (Non- Clustered Index)
    常见和链表相关的算法
  • 原文地址:https://www.cnblogs.com/510602159-Yano/p/4279270.html
Copyright © 2011-2022 走看看