Add Two Numbers

来源:互联网 发布:cnrds数据库 编辑:程序博客网 时间:2024/06/05 10:24
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

Subscribe to see which companies asked this question

题目链接:https://leetcode.com/problems/add-two-numbers/

读清题意:

  9 5 8

+2

有  11  5  8  ---------->1 6 8


    9  5   8

+  7   6  4

有 16   11  12------------->6  2  3  1

package temp;/** *  * @author Mouse * */public class Solution {public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {if (l1 == null)return l2;if (l2 == null)return l1;ListNode p = l1;ListNode ps=p;ListNode q = l2;int flag = 0;// 进位while (p != null && q != null) {if (p.val + q.val + flag >= 10) {p.val = p.val + q.val + flag - 10;flag = 1;// 表示有进位} else {p.val = p.val + q.val + flag;flag = 0;}ps=p;p = p.next;q = q.next;}// 处理p与q不相等的情况if (q != null) {ps.next=q;p=q;}if (flag > 0) {while (p != null) {if (p.val + flag >= 10) {p.val = p.val + flag - 10;flag = 1;// 表示有进位} else {p.val = p.val + flag;flag = 0;}ps=p;p = p.next;}// while}// ifif (flag > 0) {// 链表最后一个flag如果仍然为1说明有进位ListNode temp = new ListNode(1);ps.next = temp;}// ifreturn l1;}public static void main(String[] args) {ListNode l1 = new ListNode(0);//ListNode l10 = new ListNode(4);//ListNode l11 = new ListNode(3);//l1.next = l10;//l10.next = l11;ListNode l2 = new ListNode(7);ListNode l20 = new ListNode(3);//ListNode l21 = new ListNode(4);l2.next = l20;//l20.next = l21;ListNode p = addTwoNumbers(l1, l2);ListNode q = p;while (q != null) {System.out.print(" " + q.val);q = q.next;}}}


可以对比网上其它解法: http://www.2cto.com/kf/201310/252996.html



0 0
原创粉丝点击