116_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.

1:特殊情況;2:設置數組,字符串相乘,注意進位;3:注意某一位是0的情況;3:最後處理一下邊界情況


    string multiply(string num1, string num2)
    {
        if(num1.length() == 0 || num2.length() == 0)
        {
            return "";
        }
        
        int size1 = (int)num1.length();
        int size2 = (int)num2.length();
        
        if(size1 == 1)
        {
            if(num1[0] == '0')
            {
                return "0";
            }
            else if(num1[0] == '1')
            {
                return num2;
            }
        }
        
        if(size2 == 1)
        {
            if(num2[0] == '0')
            {
                return "0";
            }
            else if(num2[0] == '1')
            {
                return num1;
            }
        }
        
        string result;
        for(int i = 0; i < size1 + size2; i++)
        {
            result.push_back('0');
        }
        
        int count = 0;
        
        for(int i = size1 - 1; i >= 0; i--)
        {
            if(num1[i] == '0')
            {
                continue;
            }
            
            count = 0;
            for(int j = size2 - 1; j >= 0; j--)
            {
                int value = (num1[i] - '0') * (num2[j] - '0' ) + count + result[i+j+1] - '0';
                int temp = value % 10;
                count = value / 10;
                result[i+j+1] = temp + '0';
                
            }
            result[i] = count + '0';
        }
        
        if(result[0] == '0')
        {
            int i;
            for(i = 1; i < size1 + size2; i++)
            {
                result[i-1] = result[i];
            }
            result.pop_back();
        }
        
        
        return result;
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章