LeetCode-0002 Add Two Numbers

原题地址
题目:

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 contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

例子:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

题目大意:
两个非空链表表示的两个非空整数,单个整数按照位数逆序存储,求两个整数的和并以链表表示。

解法(scala):

/** * Definition for singly-linked list. * class ListNode(var _x: Int = 0) { * var next: ListNode = null * var x: Int = _x * } */ object Solution { def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = { var p = l1 var q = l2 val head = new ListNode() var r = head var c = 0 while (p!= null || q != null){ val sum = getValue(p) + getValue(q) r.next = new ListNode((c + sum) % 10) r = r.next c = (c + sum) / 10 p = if(p == null) p else p.next q = if(q == null) q else q.next } if(c != 0){ r.next = new ListNode(c) } r = null if(head.next == null) null else head.next } def getValue(v: ListNode): Int = { if(v == null) 0 else v.x } }

载入评论中....