首页 > 其他 > 详细

LeetCode#415-字符串相加

时间:2020-07-04 14:28:48      阅读:33      评论:0      收藏:0      [点我收藏+]
/*
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

注意:

num1 和num2 的长度都小于 5100.
num1 和num2 都只包含数字 0-9.
num1 和num2 都不包含任何前导零。
你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。

 */
public class p415 {
    public static String addStrings(String num1, String num2) {
        StringBuilder sb=new StringBuilder("");
        int i=num1.length()-1;
        int j=num2.length()-1;
        int count=0;
        while(i>=0||j>=0){
            int tmp1=i>=0?num1.charAt(i)-‘0‘:0;
            int tmp2=j>=0?num2.charAt(j)-‘0‘:0;
            int tmp=tmp1+tmp2+count;
            count=tmp/10;
            sb.append(tmp%10);
            i--;
            j--;
        }
        if(count==1)sb.append(1);
        return sb.reverse().toString();

    }

    public static void main(String[] args) {
        System.out.println(addStrings("123","4566"));
    }
}

  运行结果:

技术分享图片

LeetCode#415-字符串相加

原文:https://www.cnblogs.com/jifeng0902/p/13234718.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!