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

高精度整数加法

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

思路:从一位牛油那里得到的启发,有理有据。

public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str1=in.next();
            String str2=in.next();
            int carry=0;//进位
            StringBuilder sb=new StringBuilder();
            int i=str1.length()-1;
            int j=str2.length()-1;
            while(i>=0 || j>=0 || carry!=0){
                int x=i<0?0:(str1.charAt(i--)-'0');
                int y=j<0?0:(str2.charAt(j--)-'0');
                sb.append((x+y+carry)%10);
                carry=(x+y+carry)/10;//更新进位
            }
            System.out.println(sb.reverse());
        }
    }
全部评论

相关推荐

牛客吹哨人:哨哥晚点统一更新到黑名单:能救一个是一个!26届毁意向毁约裁员黑名单https://www.nowcoder.com/discuss/1525833
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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