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

高精度整数加法

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-09 19:35
门头沟学院 Java
洛必不可达:java的竞争激烈程度是其他任何岗位的10到20倍
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务