leetcode 2 Add Two Numbers golang
来源:互联网 发布:巴黎散步道 知乎 编辑:程序博客网 时间:2024/06/10 06:25
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]}
1 0
- leetcode 2 Add Two Numbers golang
- LeetCode题解(Golang实现)--Add Two Numbers
- LeetCode 2 - Add Two Numbers
- LeetCode 2: Add Two Numbers
- Leetcode: Add Two Numbers (2)
- [leetcode 2] Add Two Numbers
- [Leetcode] 2 - Add Two Numbers
- LeetCode 2:《Add Two Numbers》
- LeetCode | #2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- [Leetcode]2Add Two Numbers
- leetcode #2 Add Two Numbers
- leetcode-2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- [leetcode] #2 Add Two Numbers
- LeetCode-2 Add Two Numbers
- LeetCode-2-Add Two Numbers
- Leetcode[2] Add Two Numbers
- 错误:error C2259:“CxxDlg”:不能实例化抽象类
- 深度学习:径向基网络(RBF)
- 浏览器内部工作原理
- 蚁群算法
- 对字符串中的数字子串求和
- leetcode 2 Add Two Numbers golang
- c++——双向循环链表常见操作
- Android studio 调试NDK C++ 代码,遇到的问题
- (13)关卡编辑器之大纲视图
- poj 2104 主席树
- IFE2017-单个表单项的检验
- 第五天 : 启动线程和运行线程中方法的区别
- io流的概述及字节流相关类的基本使用和异常处理
- CentOS虚拟机下挂载镜像