一:题目
二:上码
// /**
// * Definition for singly-linked list.
// * public class ListNode {
// * int val;
// * ListNode next;
// * ListNode() {}
// * ListNode(int val) { this.val = val; }
// * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
// * }
// */
// class Solution {
// /**
// - 将两个链表上的节点的值均 取出来 作为两个整数
// - 将两个整数相加取得结果 将每个字符反过来赋予到一个新的链表当中。
// */
// public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// StringBuilder s1 = new StringBuilder();
// StringBuilder s2 = new StringBuilder();
// while (l1 != null) {
// s1.append(l1.val);
// l1 = l1.next;
// }
// while (l2 != null) {
// s2.append(l2.val);
// l2 = l2.next;
// }
// //将字符串反转
// s1.reverse();
// s2.reverse();
// //转换成int类型
// double num1 = Double.parseDouble(s1.toString());
// double num2 = Double.parseDouble(s2.toString());
// System.out.println("====num1"+num1);
// System.out.println("====num2"+num2);
// //相加结果
// double sumAns = num1 + num2;
// System.out.println("====sumAns"+sumAns);
// String str = String.valueOf(sumAns);
// str = str.substring(0,str.indexOf("."));
// System.out.println("====="+str);
// ListNode head = null;
// ListNode tail = null;
// for (int i = str.length() - 1; i >= 0; i--) {
// int num = str.charAt(i) - '0';
// System.out.println("====="+num);
// if (head == null) {
// head = tail = new ListNode(num);
// } else {
// tail.next = new ListNode(num);
// tail = tail.next;
// }
// }
// return head;
// }
// }
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
/**
- 这里的相加 是每个位进行相加 然后有进位的话 就是 向后面的节点相加的值进行进位
- 如果链表对应的位置没有值 那么的话 就补0
- 99999999
- 99999000
*/
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode pre = new ListNode(0);
ListNode cur = pre;
int carry= 0;//表示进位为0
while (l1 != null || l2 != null) {
int x = l1 == null ? 0 : l1.val;
int y = l2 == null ? 0 : l2.val;
int sum = x + y + carry;//两个节点的值+进位
carry = sum >= 10 ? 1 : 0;
sum = sum % 10;//如果相加大于10的话 我只是取余数
//这里我们对cur.next进行赋值 是因为 我们在cur这个对象中的属性才满足一个val,还有next
//未进行赋值
cur.next = new ListNode(sum);
cur = cur.next;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
if (carry >= 1) {
cur.next = new ListNode(1);
}
return pre.next;
}
}
这题很狗 笨办法做不出来 最后还是看了题解 rue了