package org.example; import java.util.ArrayList; import java.util.List; import java.util.Scanner; class SuperNum { public List<Integer> numList; /** * 成员变量的set方法 * @param numList */ public void setNumList(List<Integer> numList) { this.numList = numList; } /** * 从键盘输入 */ public void inputNumList() { this.numList = new ArrayList<>(); System.out.println("请输入数字"); Scanner sc = new Scanner(System.in); String inputString = sc.nextLine(); for (int i = 0; i < inputString.length(); i++) { int n = Integer.parseInt(String.valueOf(inputString.charAt(i))); numList.add(0, n); } } /** * 输出存储的数字 */ public void printNum() { for (int i = this.numList.size()-1; i >= 0; i--) { System.out.print(this.numList.get(i)); } System.out.println(); } } public class Main { public static SuperNum SumSuperNum(SuperNum num1, SuperNum num2) { List<Integer> numList1 = num1.numList; List<Integer> numList2 = num2.numList; List<Integer> newList = new ArrayList<>(); int minLen = Math.min(numList1.size(), numList2.size()); int temp = 0; // 进位标记 int thisNum; // 从个位起相加 for (int i = 0; i < minLen; i++) { thisNum = numList1.get(i) + numList2.get(i) + temp; // 还原进位标记 temp = 0; if (thisNum >= 10) { // 需要进位 temp = 1; thisNum = thisNum - 10; newList.add(thisNum); } else { // 不需要进位 temp = 0; // 还原进位标记 newList.add(thisNum); } } // 处理剩余数字 List<Integer> remainNum = numList1.size() > numList2.size() ? numList1 : numList2; for (int i = minLen; i < remainNum.size(); i++) { thisNum = remainNum.get(i) + temp; // 还原进位标记 temp = 0; if (thisNum >= 10) { // 需要进位 temp = 1; thisNum = thisNum - 10; newList.add(thisNum); } else { // 不需要进位 temp = 0; // 还原进位标记 newList.add(thisNum); } } SuperNum resultNum = new SuperNum(); resultNum.setNumList(newList); return resultNum; } public static void main(String[] args) { SuperNum superNum1 = new SuperNum(); superNum1.inputNumList(); SuperNum superNum2 = new SuperNum(); superNum2.inputNumList(); SuperNum Result = SumSuperNum(superNum1, superNum2); System.out.print("求和结果 = "); Result.printNum(); } } /** * * 42846280183517070527831839425882145521227251250327 * 55121603546981200581762165212827652751691296897789 * 97967883730498271109594004638709798272918548148116 */
标签:thisNum,java,temp,大数,int,SuperNum,加法,进位,numList From: https://www.cnblogs.com/libayu/p/17305418.html