Add Two Numbers @ LeetCode

Source: Internet
Author: User

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; // carry ListNode p1 = l1; // mark l1 position ListNode p2 = l2 ;// Mark the location of l2 ListNode ret = null; // return the linked list ListNode p3 = ret; // mark the location of the returned linked list // process the same length part 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;} // process the 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 ;} // The carry if (p1 = null & p2 = null & carry! = 0) {ListNode n = new ListNode (carry); p3.next = n;} return ret ;}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.