본문 바로가기
알고리즘/LeetCode

[LeetCode] 002. Add Two Numbers JAVA

by Bhinney 2022. 12. 16.
 

Add Two Numbers - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


📌 문제

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.

📌 방법

1️⃣ ListNode를 초기화

2️⃣ 결과를 반환할 값에 node를 대입

3️⃣ 반복문을 돌며 각 ListNode의 val를 더함

4️⃣ 나머지와 나누는 이유 = 합이 두 자리수가 될 수 있기 때문 (10 이상)

      한 자리수 이상이면, 일의 자리 수가 값이 되고 십의 자리수의 값 만큼 다음에 더해줘야 함.

5️⃣ 반복문의 조건식이 참인 동안 반복

6️⃣ 결과 반환

 

/**
 * 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) {
	/*
	 * l1 = [2,4,3]
	 * l2 = [5,6,4]
	 * result = [7,0,8]
	 */
        
        ListNode node = new ListNode(0);
        ListNode result = node;
        int sum = 0;

        while(l1 != null || l2 != null || sum > 0) { 
            if (l1 != null) {
                sum += l1.val; 
                l1 = l1.next; 
            }
            
            if (l2 != null) {
                sum += l2.val; 
                l2 = l2.next; 
            }

            node.next = new ListNode(sum % 10); 
            sum /= 10; 
            node = node.next; 
        }

        return result.next; 
    }
}

댓글