【java编程(在线笔试)】【运算】大数相加

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author frlh
 * @create 2020/06/07 15:58
 */
public class Main {
     

    static Random random = new Random();

    // 核心方法
    public static String sum(String a, String b) {
     
        int len = Math.max(a.length(), b.length());
        StringBuffer s = new StringBuffer(len + 1);
        int t = 0;
        for (int i = 1; i <= len; i++) {
     
            t += getLast(a, i) + getLast(b, i);
            s.append(t % 10);
            t /= 10;
        }
        return s.reverse().toString();
    }


    public static int getLast(String a, int last) {
     
        if (last > a.length()) return 0;
        return a.charAt(a.length() - last) - '0';
    }

    public static String createNum() {
     
        StringBuffer s = new StringBuffer().append(random.nextInt(9) + 1);
        int len = 100 + random.nextInt(100);
        for (int i = 0; i < len; i++) {
     
            s.append(random.nextInt(10));
        }
        return s.toString();
    }

    public static void run() {
     
        List<String> ss = new ArrayList<>(100);
        for (int i = 0; i < 100; i++) {
     
            ss.add(createNum());
        }
        // System.out.println(ss);

        String s = ss.get(0);
        for (int i = 1; i < ss.size(); i++) {
     
            s = sum(s, ss.get(i));
        }
        System.out.println(s);
    }


    public static void main(String[] args) {
     
        run();
        // System.out.println(sum("12", "2"));
        // System.out.println(sum("12", "9"));
        // System.out.println(sum("12", "99"));
    }

}

你可能感兴趣的:(算法,Java,java,编程,在线笔试,算法,面试)