题目描述:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.、
百度翻译后(您将得到两个表示两个非负数的链表。数字以相反的顺序存储,每个节点包含一个数字。想加这两个数字,并将其作为链接列表返回。)
例如:
1->2->3->4->5
9->8->7->6
输出:
0->1->1->1->6
(01116)
即54321+6789=61110
代码
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
String s1 = scanner.nextLine();
int size = s.length();
if (s1.length() > size) {
size = s1.length();
}
int[] arr = new int[size];
int[] brr = new int[size];
for (int i = 0; i < s.length(); i++) {
arr[i] = Integer.parseInt(s.substring(i, i + 1));
}
for (int i = 0; i < s1.length(); i++) {
brr[i] = Integer.parseInt(s1.substring(i, i + 1));
}
int tmp = 0;
for (int i = 0;i<size;i++){
int x = arr[i] + brr[i];
if (tmp == 1) {
x+=1;
tmp = 0;
}
if (x>=10){
tmp = 1;
x -=10;
}
System.out.print(x);
}
}
}
输出: