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.

    Have you been asked this question in an interview? 

    public class Solution {
        public String multiply(String num1, String num2) {
            int len1 = num1.length(), len2 = num2.length();
            //using an array to save the result of multiply and initialized as zeros 
            int[] mult = new int[len1 + len2 + 1];
            for(int i = 0; i < len1 + len2 + 1; ++i)
                mult[i] = 0;
    
            for(int j = 0; j < len1; ++j){
                int carry = 0;
                int singledigit = num1.charAt(len1 - 1 - j) - '0';
                if(singledigit != 0){
                    for(int k = 0; k < len2; ++k){
                        int product = (num2.charAt(len2 - 1 - k)-'0') * singledigit + carry 
                            + mult[len1 + len2 - j - k];
                        mult[len1 + len2 -j - k] = product % 10;
                        carry = product / 10;                     
                    }
                    if(carry != 0)
                        mult[len1 - j] = carry;
                }            
            }
            StringBuffer sbf = new StringBuffer();
            int start = 0;
            while((start < len1 + len2 + 1) && mult[start] == 0)
                ++start;        
            if(start < len1 + len2 + 1){    
                for(int i = start; i < len1 + len2 + 1; ++i)
                    sbf.append(mult[i]);
            }
            else 
                sbf.append('0');
            return sbf.toString(); 
        }
    }
    

      

  • 相关阅读:
    Kali 2020.3安装docker和vulhub
    Web渗透——身份管理测试
    Web渗透——配置管理测试
    网站信息收集
    linux修改MAC的方法
    '文件上传总结'
    美杜莎和九头蛇的对比
    渗透测试常见开放端口及利用
    Google hacking 语法
    web渗透测试基本步骤
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3612664.html
Copyright © 2011-2022 走看看