From 01c0dbb83aa5ff0324b1232e9e3ac41d256af83f Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 7 May 2024 09:25:05 +0200 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB2816.=20Double=20a=20Number?= =?UTF-8?q?=20Represented=20as=20a=20Linked=20List=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...e-a-number-represented-as-a-linked-list.kt | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 kt/double-a-number-represented-as-a-linked-list.kt diff --git a/kt/double-a-number-represented-as-a-linked-list.kt b/kt/double-a-number-represented-as-a-linked-list.kt new file mode 100644 index 0000000..f2331ed --- /dev/null +++ b/kt/double-a-number-represented-as-a-linked-list.kt @@ -0,0 +1,76 @@ +class ListNode(var `val`: Int) { + var next: ListNode? = null +} + +fun toListNode(vararg xs: Int): ListNode? { + if (xs.isEmpty()) { + return null + } + + val dummy = ListNode(0) + var node = dummy + + for (x in xs) { + val next = ListNode(x) + node.next = next + node = next + } + + return dummy.next +} + +fun linkedListEquals(head: ListNode?, xs: List): Boolean { + var node = head + for ((i, x) in xs.withIndex()) { + if (node == null) { + println("[DEBUG] $x is expected at index $i in the linked list, but is not present") + return false + } else if (node.`val` != x) { + println("[DEBUG] $x is expected at index $i in the linked list, but ${node.`val`} is present") + return false + } + + node = node.next + } + + if (node != null) { + println("[DEBUG] Linked list is longer than expected") + } + + return node == null +} + +class Solution { + fun doubleIt(head: ListNode?): ListNode? { + val dummyHead = ListNode(0) + dummyHead.next = head + + val (newHead, carry) = doubleItRec(dummyHead) + if (newHead!!.`val` > 0) { + return newHead + } + return newHead.next + } + + private fun doubleItRec(node: ListNode?): Pair { + if (node == null) { + return null to 0 + } + + val (nextHead, carry) = doubleItRec(node.next) + val current = carry + 2 * node.`val` + + val newNode = ListNode(current % 10) + newNode.next = nextHead + + return newNode to current / 10 + } +} + +fun main() { + val s = Solution() + + check(linkedListEquals(s.doubleIt(toListNode(1, 8, 9)), listOf(3, 7, 8))) + check(linkedListEquals(s.doubleIt(toListNode(9, 9, 9)), listOf(1, 9, 9, 8))) + check(linkedListEquals(s.doubleIt(toListNode(0)), listOf(0))) +}