算法(五)--两数相加

前言

仅记录学习笔记,如有错误欢迎指正。

题目

给出两个非空的链表用来表示两个非负的整数。其中它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)

  • 输出:7 -> 0 -> 8
  • 原因:342 + 465 = 807

tips:

  • 数组转链表
    LinkedList list = new LinkedList(Arrays.asList(array))
  • 链表转数组
    String[] array1= (String[]) linklist.toArray(new String [0]);

解法一

开始以为是用linkedList去写。。

 public  LinkedList<Integer> addTwoNumbers(LinkedList<Integer> l1, LinkedList<Integer> l2){
    
    
        int num1 = 0;
        int num2 = 0;
        int sum = 0 ;
        for(int i = 0 ; i<l1.size();i++){
    
    
            num1+=l1.get(i)*Math.pow(10,i);
        }
        for(int i = 0 ; i<l2.size();i++){
    
    
            num2+=l2.get(i)*Math.pow(10,i);
        }
        sum = num1 + num2;
        l1.clear();
        while(sum !=0){
    
    
            int temp = sum%10;
            l1.add(temp);
            sum/=10;
        }
        return l1;

解法二

网上的写法,需要自己先定义链表。

public class ListNode {
    
    
        int val;
        ListNode next;
        ListNode(int x) {
    
     val = x; }
    }

    public ListNode addTwoNumbers1(ListNode l1, ListNode l2) {
    
    
        ListNode dummy = new ListNode(0);

        int sum = 0; // 结果
        int more = 0; // 进位
        ListNode pre = dummy;
        while (l1 != null || l2 != null || more > 0) {
    
    
            sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + more;
            more = sum / 10;
            sum %= 10;
            ListNode node = new ListNode(sum);
            pre.next = node;
            pre = node;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        return dummy.next;
    }

    }

猜你喜欢

转载自blog.csdn.net/njh1147394013/article/details/112761625
今日推荐