1. 문제(원본)
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
Example 1:
Input: head = [1,0,1] Output: 5 Explanation: (101) in base 2 = (5) in base 10
Example 2:
Input: head = [0] Output: 0
Example 3:
Input: head = [1] Output: 1
Example 4:
Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0] Output: 18880
Example 5:
Input: head = [0,0] Output: 0
Constraints:
- The Linked List is not empty.
- Number of nodes will not exceed 30.
- Each node's value is either 0 or 1.
2. 문제
주어진 노드 클래스를 사용하여 입력된 이진수를 십진수로 변환하여 출력하라 (아래는 제공 노드 클래스)
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
3. 나의 답
class Solution {
func getDecimalValue(_ head: ListNode?) -> Int {
var resultData: String = ""
var roof = head
while roof?.next != nil {
resultData.append("\(roof!.val)")
roof = roof?.next
}
resultData.append("\(roof!.val)")
guard let returnValue = Int(resultData, radix: 2) else { return 0 }
return returnValue
}
}
4. 다른 유저의 답
#1
func getDecimalValue(_ head: ListNode?) -> Int {
var ans = 0
var node: ListNode? = head
while node != nil {
ans = ans * 2 + node!.val
node = node?.next
}
return ans
}
#2
class Solution {
func getDecimalValue(_ head: ListNode?) -> Int {
var result: Int = 0
var curNode: ListNode? = head
while curNode != nil {
result = (result << 1) | curNode!.val
curNode = curNode!.next
}
return result
}
}
5. 마무리
문제 해결에는 별 어려움은 없었지만 다른 유저의 답변을 보고 아직 많이 활용하는 방법에 대한 부족함을 느꼈다.
shift연산자는 문제 풀 때는 진짜 생각도 못했다.
이번 LeetCode를 풀면서 느낀 것은 다른 유저의 답변도 보면서 다양한 지식을 습득할 수 있는 것이 좋은 것 같다.
'알고리즘 > 해결' 카테고리의 다른 글
LeetCode657. Robot Return to Origin (0) | 2020.03.18 |
---|---|
LeetCode1266. Minimum Time Visiting All Points (0) | 2020.03.15 |
LeetCode1323. Maximum 69 Number (0) | 2020.03.08 |
LeetCode1365. How Many Numbers Are Smaller Than the Current Number (0) | 2020.03.08 |
LeetCode1221. Split a String in Balanced Strings (0) | 2020.02.23 |