Yet another scala solution


  • 0
    Z

    The ListNode defined by leetcode is in java style and really hard to use for me. It force me to use implicits : )

    object ListNode {
      def apply(x: Int, next: ListNode): ListNode = {
        val n = new ListNode(x)
        n.next = next
        n
      }
    
      implicit def listnode2list(x: ListNode): List[Int] = x match {
        case null => Nil
        case n => n.x :: listnode2list(n.next)
      }
    
      implicit def list2listnode(l: List[Int]): ListNode = l match {
        case head :: tail => ListNode(head, list2listnode(tail))
        case Nil => null
      }
    }
    
    object Solution {
      import ListNode.{list2listnode, listnode2list}
    
      def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = addTwoNumbers(l1, l2, 0)
    
      def addTwoNumbers(l1: List[Int], l2: List[Int], c: Int): List[Int] = (l1, l2, c) match {
        case (Nil, Nil, 0) => Nil
        case (Nil, Nil, 1) => List(1)
        case (h1 :: t1, Nil, _) => (h1 + c) % 10 :: addTwoNumbers(t1, Nil, (h1 + c) / 10)
        case (Nil, h2 :: t2, _) => (h2 + c) % 10 :: addTwoNumbers(Nil, t2, (h2 + c) / 10)
        case (h1 :: t1, h2 :: t2, _) => (h1 + h2 + c) % 10 :: addTwoNumbers(t1, t2, (h1 + h2 + c) / 10)
      }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.