文章--LeetCode算法--AddTwoNumbers
AddTwoNumbers
问题描述
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
示例
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
解决思路
思路:数字进位问题,该位有效值为值%10,进位值为值/10。可以使用一个变量记录进位值。
实现代码
package com.leetcode.play;
/**
* You are given two non-empty linked lists representing two non-negative integers. 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.
* You may assume the two numbers do not contain any leading zero, except the number 0 itself.
*
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 0 -> 8
*/
public class AddTwoNumbers {
public static void main(String[] args) {
ListNode node = new ListNode();
ListNode node2 = new ListNode();
ListNode node3 = new ListNode();
node.val = 2;
node.next = node2 ;
node2.val = 4;
node2.next = node3;
node3.val = 3;
node3.next = null ;
ListNode node4 = new ListNode();
ListNode node5 = new ListNode();
ListNode node6 = new ListNode();
node4.val = 5;
node4.next = node5 ;
node5.val = 6;
node5.next = node6;
node6.val = 4;
node6.next = null ;
ListNode listNode = addTwoNumbers(node,node4);
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
ListNode lResult = new ListNode(0);
ListNode lPointer = lResult;
while (l1 != null || l2 != null) {
int n1 = 0, n2 = 0;
if (l1 != null) {
n1 = l1.val;
l1 = l1.next;
}
if (l2 != null) {
n2 = l2.val;
l2 = l2.next;
}
int temp = n1 + n2 + carry;
carry = temp / 10;
temp %= 10;
lPointer.next = new ListNode(temp);
lPointer = lPointer.next;
}
if (carry > 0) {
lPointer.next = new ListNode(carry);
}
return lResult.next;
}
public static class ListNode{
public int val ;
public ListNode next ;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
}

浙公网安备 33010602011771号