您的位置:首页 > 其它

LeetCode Add Two Number

2015-07-11 10:10 459 查看
第二天,记录自己的刷题经历,第二题

题目:

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

思路:

智商实在让人捉急,看到题目半天没董是什么意思,后来才知道是一个链表代表一个数,并且该数在链表中是按照逆序的方式存储,计算这两个数之和。


智商如此让人捉急,是不是应该赶紧转行。


一把鼻涕一把泪的坎坎坷坷把这个破东西给搞定了,连基本的java中ListNode都不会用,肿么办肿么办。。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int temp;
        int overflow = 0;
        ListNode newHead = new ListNode(0);
        ListNode l3 = newHead;
        while(l1 !=null || l2!= null){   //居然能粗心把这里的while写成for,我是猪么
            int val1=0 , val2=0;
            if(l1 != null){
                 val1 = l1.val;
                 l1 = l1.next; 
            }
            if(l2 != null){
               val2 = l2.val;
               l2 = l2.next;
            }
            temp = val1 + val2 + overflow;
            overflow = temp /10;
            l3.next = new ListNode(temp%10);
            l3 = l3.next;
            if(overflow !=0){
                l3.next =new ListNode(overflow);
            }
        }
     return  newHead.next;   //设一个头部的原因是最终要把头部指针返回去,p3一直往后挪给链表加数据
    }
}
学习人家的代码优化下我这重复性这么强的代码好么。。。

将个个位上的和 和 进位 用一个变量来表示,减少代码的重复性 。Runtime:
452 ms


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int temp = 0;
      //  int overflow = 0;
        ListNode newHead = new ListNode(0);
        ListNode l3 = newHead;
        while(l1 !=null || l2!= null){   //居然能粗心把这里的while写成for,我是猪么
            if(l1 != null){
                 temp += l1.val;
                 l1 = l1.next; 
            }
            if(l2 != null){
               temp += l2.val;
               l2 = l2.next;
            }
          //  temp = val1 + val2 + overflow;    //一个temp临时变量就可以搞定,没必要搞两个。
            l3.next = new ListNode(temp%10);
            temp = temp /10;
            l3 = l3.next;
            if(temp !=0){
                l3.next =new ListNode(temp);
            }
        }
     return  newHead.next;   //设一个头部的原因是最终要把头部指针返回去,p3一直往后挪给链表加数据
    }
}


伤心,刚开始连java的l1.val l1.next都不会用,还写成l1->val li->next;
像这种创建下一个l3.next, 不能简单的l3 = l3.next; 需要使用 l3.next = new ListNode(val) 来创建,其中里面的val表示链表该节点的数值。

亲,你好一说 你会java,你是搞android开发的吗?





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: