当前位置:编程学习 > JAVA >>

Add Two Numbers @LeetCode

package Level3;

import Utility.ListNode;

/**
 * 
 * Add Two Numbers 
 *
 * 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
 */
public class S2 {

	public static void main(String[] args) {
		ListNode l1 = new ListNode(2);
		ListNode x2 = new ListNode(4);
		ListNode x3 = new ListNode(3);
		l1.next = x2;
		x2.next = x3;
		
		ListNode l2 = new ListNode(5);
		ListNode y2 = new ListNode(6);
		ListNode y3 = new ListNode(4);
		l2.next = y2;
		y2.next = y3;
		
		ListNode ret = addTwoNumbers(l1, l2);
		ret.print();
	}
	
	public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		int carry = 0;			// 进位
		ListNode p1 = l1;		// 标记l1的位置
		ListNode p2 = l2;		// 标记l2的位置
		ListNode ret = null;	// 返回链表
		ListNode p3 = ret;	// 标记返回链表的位置
		
		// 处理相同长度部分
		while(p1!=null && p2!=null){
			int add = p1.val + p2.val + carry;
			if(add < 10){
				carry = 0;
			}else{
				add -= 10;
				carry = 1;
			}
			ListNode n = new ListNode(add);
			if(ret == null){
				ret = n;
				p3 = n;
			}else{
				p3.next = n;
				p3 = n;
			}
			p1 = p1.next;
			p2 = p2.next;
		}

		// 处理不同长度部分
		while(p1 != null){
			int add = p1.val + carry;
			if(add < 10){
				carry = 0;
			}else{
				add -= 10;
				carry = 1;
			}
			ListNode n = new ListNode(add);
			p3.next = n;
			p3 = n;
			p1 = p1.next;
		}
		
		while(p2 != null){
			int add = p2.val + carry;
			if(add < 10){
				carry = 0;
			}else{
				add -= 10;
				carry = 1;
			}
			ListNode n = new ListNode(add);
			p3.next = n;
			p3 = n;
			p2 = p2.next;
		}
		
		// 处理最后可能会出现的进位
		if(p1==null && p2==null && carry!=0){
			ListNode n = new ListNode(carry);
			p3.next = n;
		}
		
		return ret;
	}

}

 

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,