본문 바로가기

Algorithms/LeetCode

[Java] LeetCode 문제 풀이 : Problem2 Add Two numbers(Linked List)

--- 문제 ---

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.

 

0 혹은 양수로 이루어진 값을 표현하는 무조건 1개 이상의 노드가 포함된 링크드 리스트 2개가 주어질 것이다. 대신 반대의 순서로 숫자들이 저장되어 있고, 그 각 노드들은 하나의 0~9 사의 값으로 이루어져 있다. 두가지 링크드 리스트로 표현된 숫자들을 더하고 그 더한 값을 똑같은 링크드 리스트 형태로 반환하라. 2개의 숫자들은 0으로 시작할 수 없다 라고 가정한다. (예로 0101 -> 101 로 표현될 것이다.)

( 문제 사이트에 있는 그림을 보면 더욱 이해가 쉬울 것입니다.)

 

--- 코드 ---

 

import java.util.*;

public class Leet2 {

	public static void main(String[] args) {
		// test case
		ListNode l1 = new ListNode(9,new ListNode(9)); //99
		ListNode l2 = new ListNode(1, new ListNode(9,new ListNode(1))); //191
		
		// initialize
		ListNode answer = new ListNode(0);
		ListNode current = answer;
		ListNode obj1 = l1;
		ListNode obj2 = l2;
		int carry = 0;
		
		// 2. repeat until the end of the list
		while(obj1!=null || obj2!=null) {
			current.next = new ListNode();
			current = current.next;
			// 2-1. extract one element if it exists
			int n1 = (obj1!=null)? obj1.val : 0;
			int n2 = (obj2!=null)? obj2.val : 0;
			
			// 2-2. sum & carry
			int sum = n1 + n2 + carry;
			carry = (int)(sum / 10);
			sum = sum % 10;
			
			// 2-3. save sum to the next object as result
			current.val=sum;
			
			obj1 = (obj1!=null)? obj1.next : obj1;
			obj2 = (obj2!=null)? obj2.next : obj2;
			
			
		}
		
		// 3. save the 1 if carry exists
		if(carry==1) {
			current.next=new ListNode(1);
		}
		
		// return answer.next;
		// confirm the result
		while(answer.next!=null) {
			System.out.print(answer.next.val+" ");
			answer = answer.next;
		}
		
	}

}

 class ListNode {
     int val;
     ListNode next;
     ListNode() {}
     ListNode(int val) { this.val = val; }
     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 }

---결과---

 

 

--- 출처 ---

 

leetcode.com/problemset/all/

 

반응형

'Algorithms > LeetCode' 카테고리의 다른 글

[Java] LeetCode 문제 풀이 : Problem1 Two Sum (Array)  (0) 2021.02.14