博主头像
7024w的自留地

觉宇宙之无穷,识盈虚之有数

Leetcode 2.两数相加

最开始以为是向前进1位卡了很久,结果原来是我想错了...

/**

  • Definition for singly-linked list.
  • public class ListNode {
  • int val;
  • ListNode next;
  • ListNode() {}
  • ListNode(int val) { this.val = val; }
  • ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  • }
    */

class Solution {

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    int i=0;
    int[] nums = new int[100];
    for(;l1!=null || l2!=null;i++){
        int a = l1==null?0:l1.val;
        int b = l2==null?0:l2.val;
        nums[i] = a+b;
        if(l1 != null) l1 = l1.next;
        if(l2 != null) l2 = l2.next;
    }
    ListNode res = new ListNode(0,null);
    ListNode b = res;
    boolean last=false;
    int k;
    for (int j = 0; j < i; j++) {
        if(nums[j] >=10){
            if(j==i-1){
                last=true;
            }
            k=nums[j]-10;
            nums[j+1] = nums[j+1] +1;
        }else{
            k = nums[j];
        }
            res.next = new ListNode(k,null);
            res = res.next;
    }
    if(last){
        res.next = new ListNode(1,null);
        res = res.next;
    }
    return b.next;
}

}

发表新评论