Java 两数相加

问题

给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字0之外,这两个数都不会以0开头。
示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

代码

public class AddTwoNumbers {
    public static void main(String[] args) {
        ListNode l1=new ListNode(9);
        ListNode l2=new ListNode(1);
        l2.next=new ListNode(9);
        l2.next.next=new ListNode(9);
        System.out.println(addTwoNumbers(l1,l2).next.next.next.val);
    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        HashMap<Integer, Integer> resultMap= new HashMap<>();
        int tempNum=(l1.val+l2.val)%10;
        resultMap.put(0, tempNum);
        tempNum=(l1.val+l2.val)/10;
        ListNode tempL1=null;
        ListNode tempL2=null;
        try {
            tempL1=l1.next;
        } catch (Exception e) {
            tempL1=null;
        }
        try {
            tempL2=l2.next;
        } catch (Exception e) {
            tempL2=null;
        }
        int i=0;
        while(tempL1!=null || tempL2!=null) {
            i++;
            int num1;
            int num2;
            if(tempL1==null) {
                num1=0;
            }else {
                num1=tempL1.val;
            }
            if(tempL2==null) {
                num2=0;
            }else {
                num2=tempL2.val;
            }
            resultMap.put(i, (tempNum+num1+num2)%10);
            tempNum=(tempNum+num1+num2)/10;
            try {
                tempL1=tempL1.next;
            } catch (Exception e) {
                tempL1=null;
            }
            try {
                tempL2=tempL2.next;
            } catch (Exception e) {
                tempL2=null;
            }
        }
        if(tempNum>0) {
            i++;
            resultMap.put(i, tempNum);
        }
        ListNode result=creatListNode(i,resultMap);
        return result;
    }
    public static ListNode creatListNode(int i, HashMap<Integer, Integer> resultMap) {
        ListNode result=new ListNode(resultMap.get(i));
        while(i>0) {
            ListNode temp=new ListNode(resultMap.get(--i));
            temp.next=result;
            result=temp;
        }
        return result;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 2. 两数相加 Description 给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的...
    狂吃不胖温同学阅读 867评论 0 1
  • LeetCode-链表 链表(Linked List)是一种常见的基础数据结构,是一种线性表,但是并不会按线性的顺...
    raincoffee阅读 1,273评论 0 6
  • 题目:2. 两数相加 难度:中等 分类:链表 解决方案:链表的遍历 题目描述 给出两个非空的链表用来表示两个非负的...
    编程半岛阅读 1,069评论 0 2
  • 1. 找出数组中重复的数字 题目:在一个长度为n的数组里的所有数字都在0到n-1的范围内。数组中某些数字是重复的,...
    BookThief阅读 1,829评论 0 2
  • 你是否还在为手机里的照片无处安放而焦虑? 每当32G内存的手机提示主人内存空间不足的时候,你是否心痛的无法呼吸。面...
    不恋水的鱼阅读 118评论 0 1