字符串相乘 (Multiply Strings)

 

思路:

// @Title: 字符串相乘 (Multiply Strings)
// @Author: qisiii
// @Date: 2024-05-10 17:44:48
// @Runtime: 30 ms
// @Memory: 44.4 MB
// @comment: 
// @flag: 
class Solution {
    public String multiply(String num1, String num2) {
        String result="0";
        if(num1.equals("0")||num2.equals("0")){
            return result;
        }
        if(num1.length()==1){
            if(num1.equals("1")){
                return num2;
            }
            int n=num1.charAt(0)-'0',jin=0;
            char[] res=new char[num2.length()+1];
            for(int i=num2.length()-1;i>=0;i--){
                int cur=num2.charAt(i)-'0';
                int sum=cur*n+jin;
                jin=sum/10;
                res[i+1]=(char)(sum%10+'0');
            }
            res[0]=(char)(jin+'0');
            result=new String(res);
            if(res[0]=='0'){
                return result.substring(1);
            }
            return result;
        }else{
            int cur=num1.length()-1;
            for(int i=num1.length()-1;i>=0;i--){
                char c=num1.charAt(i);
                String temp=multiply(c+"",num2);
                if(!temp.equals("0")){
                    temp=addZero(temp,num1.length()-1-cur);
                    result=addStr(result,temp);
                }
                cur--;
            }
        }
        return result;
    }
    public String addZero(String str,int size){
        while(size>0){
            str=str+"0";
            size--;
        }
        return str;
    }
    public String addStr (String s, String t) {
        System.out.println(s+"+"+t);
        // write code here
        if(s.length()==0||t.length()==0){
            return s+t;
        }
        int max=Math.max(s.length(),t.length());
        char[] result= new char[max+1];
        int sl=s.length()-1;
        int tl=t.length()-1;
        int jin=0;
        while(sl>=0||tl>=0){
            int svalue=sl>=0?s.charAt(sl)-'0':0;
            int tvalue=tl>=0?t.charAt(tl)-'0':0;
            int cur=(svalue+tvalue+jin)%10;
            jin=(svalue+tvalue+jin)/10;
            result[max]=(char) (cur+'0');
            sl--;tl--;max--;
        }
        result[max]=(char)(jin+'0');
        return handleZero(result);
    }

    public String handleZero(char[] result){
        int firstN0=0;
        while(firstN0<result.length&&result[firstN0]=='0'){
            firstN0++;
        }
        if(firstN0==result.length){
            return "0";
        }
        return new String(result).substring(firstN0);
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18