leetcode 2 Add Two Numbers golang

本文介绍了一种解决两数相加问题的方法,通过将链表转化为整数,进行加法运算后再转换回链表形式。具体步骤包括:首先将两个链表的数值存储到切片中;其次,对切片进行相加并处理进位;最后,将结果切片连接成链表返回。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

解题思路:
先把两个连表放在slice中,对两个slice进行相加进位放在新的slice中,再把slice连接成连表。
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {

    sl1 := make([] int ,0,4) //存第一个连表的slice
    sl2 := make([] int ,0,4) //存第二个连表的slice

    temp1 := l1 //第一个连表的指针
    temp2 := l2 

    //循环吧第一个连表放进slice
    for {
         sl1 = append(sl1,temp1.Val)
           if(temp1.Next == nil ){
            break
        }
            temp1 = temp1.Next
    }

    for {
         sl2 = append(sl2,temp2.Val)
         if(temp2.Next == nil ){
            break
        }
        temp2 = temp2.Next
    }

    s := make([]ListNode ,0,5) //最终存放的连表

    len1 := len(sl1)
    len2 := len(sl2)
    var big [] int
    var small [] int  // 找到比较长的连表

    if len1 > len2 {
        big = sl1
        small = sl2
    }else{
        big = sl2
        small = sl1
    }

    x := 0  

    //把两个slice的值相加 
    for i , bigValue := range big{

        var smallValue int  //长度小的slice没有了就加 0 
        if i < len(small){
            smallValue = small[i]
        }else{
            smallValue = 0
        }
       bigValue = bigValue + x + smallValue //每次加上进位的值
       realValue := bigValue % 10
       x = bigValue / 10

       s = append(s,ListNode{realValue,nil}) //放在要返回的slice中
    } 

    if x != 0 {
        s = append(s,ListNode{x,nil}) //最后相加进了一位
    }

    cnt := len(s)
    //连接成连表
    for i := cnt - 2 ; i >= 0 ;i--{
        s[i].Next = &s[i + 1]
    }

    return  &s[0]

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值