LeetCode题解2-两数相加
踩过的坑
既往写C语言算法时,去除整数的最低位习惯使用直接除,比如88/10=8,而js的number是浮点数,所以要注意这个时候要做一个取整操作。Math.floor
条件反射的方法(错误):暴力取和
思路
将两个链表转化成整数,相加后再把结果转换成链表
此思路比较直接,但有一个比较严重的问题是:JS的数字只有number类型//todo check对不对,且长度只有64位,表达范围有限。此题最后几个用例的数字链表非常长,也就是说此场景不适用。
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
let l1Number = l1.val, l2Number = l2.val, pointer = l1.next;
let i = 1;
while(pointer) {
l1Number = l1Number + pointer