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

高精度整数加法

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


// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String s1 = in.nextLine();
        String s2 = in.nextLine();
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();
        char[] res = new char[Math.max(c1.length, c2.length)+1];
        int l1 = c1.length-1;
        int l2 = c2.length-1;
        int count = Math.max(c1.length, c2.length);
        while(l1 >= 0 && l2 >= 0){
            int sum = res[count] + c1[l1] + c2[l2] - (2*'0');
            if(sum >= 10){
                sum = sum - 10;
                res[count-1] = 1;
            }
            res[count] = (char)(sum + '0');
            l1--;
            l2--;
            count--;
        }
        if(res[count] == 1){
            res[count] = '1';
        }
        if(l2 >= 0){
            for(int i = l2; i>=0; i--){
                if(res[count] == '1'){
                    if(res[count] + c2[i] - 2*'0' >= 10){
                        res[count] = '0';
                        res[count-1] = '1';
                    }else{
                        res[count] = (char)(c2[i]+1);
                    }
                    
                }else{
                    res[count] = (char)c2[i];
                }
                count--;
            }
        }else if(l1 >= 0){
            for(int i = l1; i>=0; i--){
                if(res[count] == '1'){
                    if(res[count] + c1[i] - 2*'0' >= 10){
                        res[count] = '0';
                        res[count-1] = '1';
                    }else{
                        res[count] = (char)(c1[i]+1);
                    }
                    
                }else{
                    res[count] = (char)c1[i];
                }
                count--;
            }
        }
        String ans = String.valueOf(res);
        if(ans.charAt(0) < '0' || ans.charAt(0) > '9'){
            ans = ans.substring(1);
        }
        System.out.println(ans);
    }
}
全部评论

相关推荐

10-19 00:57
门头沟学院 Java
我不是嘉心糖捏:我刚收到面试捏
投递360集团等公司6个岗位
点赞 评论 收藏
分享
昨天 14:16
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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