程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode | Add Two Numbers

LeetCode | Add Two Numbers

編輯:C++入門知識

題目

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

分析

按照題目要求求和,注意最高位是否是進位得到的1.

代碼

public class AddTwoNumbers {
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		ListNode dummy = new ListNode(0);
		ListNode p = dummy;
		int carry = 0;
		while (l1 != null && l2 != null) {
			int sum = carry + l1.val + l2.val;
			carry = 0;
			if (sum >= 10) {
				carry = 1;
				sum -= 10;
			}
			p.next = new ListNode(sum);
			p = p.next;
			l1 = l1.next;
			l2 = l2.next;
		}
		if (l1 == null) {
			l1 = l2;
		}
		while (l1 != null) {
			int sum = carry + l1.val;
			carry = 0;
			if (sum >= 10) {
				carry = 1;
				sum -= 10;
			}
			p.next = new ListNode(sum);
			p = p.next;
			l1 = l1.next;
		}
		p.next = carry == 1 ? new ListNode(1) : null;
		return dummy.next;
	}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved