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.(这个就是两个字符串相乘,给出结果)

public String multiply(String num1, String num2)


问题分析:嗯,我们可以用到Integer.parseInt(),把两个字符串变成整型数,然后相乘返回结果。你相信这题可以这么做吗?呵呵....:-)

这题本质就是一个大数相乘。给出的Note就说这个数字可以特别大。这题并不是特别难,你小学的时候乘法竖式怎么做这里就怎么做。一位一位的乘,然后结果相加。所以我做了两个helper函数,一个是大数相加,另一个是一个数乘以一个个位数。给出代码如下:

    public String multiplysinglebit(String num1, int singlebit,int bitno){//这个bitno其实就表示十进制你后面屁股跟多少个0。
        StringBuilder res = new StringBuilder();
        int next = 0;
        for(int i = num1.length() - 1; i >= 0; i--){
            int curbit = num1.charAt(i) - '0';
            curbit = curbit * singlebit + next;
            next = curbit / 10;
            curbit %= 10;
            res.append(curbit + "");
        }
        if(next != 0)
            res.append(next + "");
        res.reverse();//
        for(int i = 0; i < bitno; i++)
            res.append("0");
        return res.toString();
    }
    
    public String addString(String num1, String num2){
        StringBuilder res = new StringBuilder();
        int next = 0, curbit = 0;
        for(int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0; i--, j--){
            curbit = 0;
            if(i >= 0){
                curbit += num1.charAt(i) - '0';
            }
            if(j >= 0){
                curbit += num2.charAt(j) - '0';
            }
            curbit += next;
            next = curbit > 9 ? 1 : 0;
            curbit %= 10;
            res.append(curbit + "");
        }
        if(next != 0)
            res.append(next + "");
        res.reverse();
        return res.toString();
    }
    
    public String multiply(String num1, String num2) {
        String res = "0";
        if(num1.equals("0") || num2.equals("0"))
            return res;
        for(int i = num2.length() - 1; i >= 0; i--){
            String curres = multiplysinglebit(num1, num2.charAt(i) -'0', num2.length() - 1 - i);
            res = addString(res, curres);
        }
        return res;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值