iT邦幫忙

2021 iThome 鐵人賽

DAY 14
0
AI & Data

想到甚麼打甚麼系列 第 14

找LeetCode上簡單的題目來撐過30天啦(DAY14)

  • 分享至 

  • xImage
  •  

醫生說我很健康/images/emoticon/emoticon07.gif真是太好了呢,今日題目如下

**題號:2 標題:Add Two Numbers 難度:Medium

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]

Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

Constraints:
• The number of nodes in each linked list is in the range [1, 100].
• 0 <= Node.val <= 9
• It is guaranteed that the list represents a number that does not have leading zeros.

我的程式碼

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    int count = 0;
    int a,b;
    ListNode result = new ListNode();
    ListNode result2 = new ListNode();
    ListNode head = result;
    ListNode tail = result;
    int c = 0;
    while(l1 != null || l2 != null){
        ListNode temp = new ListNode();
        if(l1 != null && l2 != null){
            a=l1.val; b=l2.val;
        }else if(l1 == null){
            a=0;b=l2.val;
        }else{
            a=l1.val; b=0;
        }
        System.out.println(a +"," +b+","+count);
        temp.val = (a+b+count)%10;
        //System.out.println(temp.val);
        
        if(head==null){
            head = temp;
            tail = temp;
            System.out.println(temp.val);
        }else{
            tail.next = temp;
            tail =temp;
        }
        
        
        if((a+b+count)/10 > 0){
            count = 1;
        }else{
            count = 0;
        }
        if(l1 !=null){
           l1 = l1.next; 
        }
        if(l2 !=null){
           l2 = l2.next; 
        }
        
        if(l2 ==null && l1 ==null && count ==1){
            ListNode temp2 = new ListNode();
            temp2.val = 1;
            tail.next = temp2;
            tail =temp2;
        }
        
    }
    result2 = result.next;
    return result2;
    }
}

花比較久的時間在
linklist上網查了一下怎麼用,雖然修修改改是把這題寫完了,之後有時間要來好好瞭解linklist怎麼用阿

DAY14心得
我還得念書,勸說自己一點躺平/images/emoticon/emoticon02.gif


上一篇
找LeetCode上簡單的題目來撐過30天啦(DAY13)
下一篇
找LeetCode上簡單的題目來撐過30天啦(DAY15)
系列文
想到甚麼打甚麼30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言