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

高精度整数加法

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));
        }
    }
}
全部评论

相关推荐

头像
10-15 22:27
已编辑
门头沟学院 C++
罗格镇的小镇做题家:我投了hr打电话来说学历太低了不符合要求,建议投荣耀,结果荣耀也投了一定水花没有,非本211硕
投递华为等公司10个岗位
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务