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

高精度整数加法

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

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) { 
            String a = in.next();
            String b = in.next();
            boolean f = a.length()>=b.length();
            boolean flag = false;
            char[] cBig = f?a.toCharArray():b.toCharArray();
            char[] cSmall = f?b.toCharArray():a.toCharArray();
            //相加后的字符数组
            char[] newC = new char[cBig.length+1];
            Arrays.fill(newC,'0');
            int t = 0;
            //以短字符串为基准,分别将两字符串从后面的每一个字符相加
            for(int i = cSmall.length-1; i>=0; i--){
                if(flag){
                    t = cBig[i+cBig.length-cSmall.length] + cSmall[i] + 1 - 48 - 48;
                }else{
                    t = cBig[i+cBig.length-cSmall.length] + cSmall[i] - 48 - 48;
                }
                flag = false;
                //相加大于10,进位
                if(t>=10){
                    flag = true;
                    t -= 10;
                }
                newC[i+cBig.length-cSmall.length+1] = (char)(t + 48);
            }
            //短字符串相加完成后,将长字符串剩余字符给newC
            int j = newC.length-cSmall.length-1;
            for(; j>=newC.length-cBig.length; j--){
                if(flag){
                    t = (char)(cBig[j-1] + 1 - 48);
                    flag = false;
                    if(t>=10){
                        flag = true;
                        t -= 10;
                    }
                    newC[j] = (char)(t + 48);
                }else{
                    newC[j] = cBig[j-1]; 
                }
            }
            if(flag){
                newC[0] = (char)1+48;
                System.out.print(String.copyValueOf(newC));
            }else{
                System.out.print(String.copyValueOf(newC).substring(1,newC.length));
            }
            
        }
    }
}
全部评论

相关推荐

07-02 18:09
门头沟学院 Java
苍穹外卖和谷粒商城这俩是不是烂大街了,还能做吗?
想去重庆的鸽子在吐槽:你不如把这俩做完自己搞明白再优化点再来问 何必贩卖焦虑
点赞 评论 收藏
分享
头顶尖尖的程序员:我是26届的不太懂,25届不应该是找的正式工作吗?为什么还在找实习?大四还实习的话是为了能转正的的岗位吗
点赞 评论 收藏
分享
06-02 15:17
门头沟学院 Java
心爱的idea:怎么会呢 应该是打招呼有问题 问就说实习6个月全国可飞随时到岗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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