/**
 * Example:
 * var li = ListNode(5)
 * var v = li.`val`
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */
class Solution {
    fun getCurrentDigit(number: Int) : Int {
        if (number > 9) {
            return number.toString().substring(1, 2).toInt()
        }
        return number.toString().substring(0, 1).toInt()
    }
    
    fun getCarry (number: Int) : Int? {
        if (number > 9) {
            return number.toString().substring(0, 1).toInt()
        }
        return 0
    }
    
    fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
        var listOne = l1
        var listTwo = l2
        
        
        var resultListHead = ListNode(-1)
        var resultList = resultListHead
        var carry = 0
        while(listOne != null || listTwo != null) {
            var currentSum = 0
            
            if (listOne != null) {
                currentSum += listOne!!.`val`
            }
            if (listTwo != null) {
                currentSum += listTwo!!.`val`
            }
            
            currentSum += carry!!
        
            
            var currentDigit = currentSum % 10
            carry = currentSum / 10
            resultList.next = ListNode(currentDigit)
            
            resultList = resultList.next
            
            if (listOne != null) listOne = listOne!!.next
            if (listTwo != null) listTwo = listTwo!!.next
        }
        if (carry != 0) {
            resultList.next = ListNode(carry)
        }
        return resultListHead.next
    }
}