题解 | #大数加法#

大数加法

https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475

package test2;
//以字符串的形式读入两个数字,编写一个函数计算它们的和,以字符串形式返回。
public class BigAdd {
    public static void main(String[] args) {
        BigAdd bigAdd = new BigAdd();
        String solve = bigAdd.solve("1", "99");
        System.out.println(solve);
    }
    public String solve (String s, String t) {
        int longLen = s.length()>=t.length() ? s.length():t.length();
        //长短字符串确定
        String longStr = s.length()>=t.length() ? s:t;
        String shortStr = s.length()< t.length() ? s:t;
        //将长的和段字符串补齐
        StringBuffer short_buffer = new StringBuffer(shortStr);
        for (int i = shortStr.length(); i < longStr.length(); i++) {
            short_buffer.insert(0,"0");
        }
        String t1 = short_buffer.toString();
        //System.out.println(short_buffer);
        int[] res = new int[longLen+1];
        int up=0;
        StringBuffer buffer = new StringBuffer();
        for (int i = longStr.length()-1; i >=0 ; i--) {

            int curRes = res[i]+ (longStr.charAt(i)-'0')+(t1.charAt(i)-'0')+up;
            buffer.append(curRes%10);
            up = curRes / 10;
        }
        if(up!=0){
            buffer.append(up);
        }
        //System.out.println(buffer.reverse().toString());
        return buffer.reverse().toString();
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务