题解 | #高精度整数加法#

高精度整数加法

http://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6

import java.util.Scanner;

public class Main {

    public static String getSum(String s1, String s2) {

        String sum = "";
        char[] c1, c2;
        //add_bit来自低位保存进位值
        int n1, n2, add_bit = 0;
        if (s1.length() < s2.length()) {
            c1 = s1.toCharArray();
            c2 = s2.toCharArray();
        } else {
            c1 = s2.toCharArray();
            c2 = s1.toCharArray();
        }

        int i = c2.length - 1,j = c1.length - 1;
        while (i >= 0) {
            if (j < 0)
                n1 = 0;
            else n1 = c1[j] - '0';
            n2 = c2[i] - '0';
            //(n1+n2+add_bit)%10当前计算结果,省去进位
            sum = (n1 + n2 + add_bit) % 10 + sum;
            add_bit = (n1 + n2 + add_bit) / 10;
            i--;
            j--;
        }
        if (add_bit > 0)
            sum = add_bit + sum;
        return sum;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String s1 = in.next();
            String s2 = in.next();
            System.out.println(getSum(s1, s2));
        }
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-08 12:05
俺不中了,BOSS遇到了一个hr,我觉得我咨询的问题都很正常吧,然后直接就被拒绝了???
恶龙战士:你问的太多了,要不就整理成一段话直接问他,一个一个问不太好
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 11:30
找工作7个月,投了7000封,3段世界五百强实习,才有一个offer,牛油们肯定比我强吧
码农索隆:不对不对不对,实习经历这么厉害,简历也没少投,问题出在哪呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务