您的位置 首页 golang

Golang刷题找工作 Leetcode-2

题目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.

给两个非空的 链表 代表两个非负整数,返回他们相加之后的逆序结果

例如

输入:2->4->3和5->6->4

输出:7->0->8

思路

注意的问题:

  1. 进位
  2. 两个list的长度不一定相等

code

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
result := &ListNode{0,  nil }
cursor := result
leftBit, rightBit, carryBit := 0, 0, 0
for l1 != nil || l2 != nil || carryBit > 0 {
if l1 != nil {
leftBit = l1.Val
l1 = l1.Next
} else {
leftBit = 0
}
if l2 != nil {
rightBit = l2.Val
l2 = l2.Next
} else {
rightBit = 0
}
//考虑有进位的情况
cursor.Val = (leftBit + rightBit + carryBit) % 10
carryBit = (leftBit + rightBit + carryBit) / 10
if l1 != nil || l2 != nil || carryBit > 0 {
cursor.Next = &ListNode{0, nil}
cursor = cursor.Next
}
}
return result
}
 

更多内容请移步我的repo:

文章来源:智云一二三科技

文章标题:Golang刷题找工作 Leetcode-2

文章地址:https://www.zhihuclub.com/101053.shtml

关于作者: 智云科技

热门文章

网站地图