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

高精度整数加法

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

import java.util.*;
    
public class Main{
    public static void main(String[] args) throws Exception{
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            char[] numA = scanner.nextLine().trim().toCharArray();
            char[] numB = scanner.nextLine().trim().toCharArray();
            char[] numL = numA.length >= numB.length ? numA : numB;
            char[] numS = numA.length < numB.length ? numA : numB;
            char[] res = new char[numL.length+1];
            res[0] = ' ';
            boolean add = false; //表示是否进位
            for (int i = 1; i <= numL.length; i++) {
                int temp = numL[numL.length-i] + (i <= numS.length ? numS[numS.length-i]-'0' : 0);
                if(add) temp++;
                res[res.length - i] = (char)temp;
                if (res[res.length - i] > '9') {
                    res[res.length - i] = (char)(res[res.length - i] - 10);
                    add = true;
                } else {
                    add = false;
                }
            }
            if (add) res[0] = '1';
            for (char c : res) {
                if (c != ' ') {
                    System.out.print(c);
                }
            }
            System.out.println();
        }   
        scanner.close();
    }    
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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