The two numbers and return it as a linked list

来源:互联网 发布:3d模型制作软件 编辑:程序博客网 时间:2024/05/20 09:45

/**
*

 
* 原题
* You are given two linked lists representing two non-negative numbers.
* 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.
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 0 -> 8
*
* 题目大意
* 有两个单链表,代表两个非负数,每一个节点代表一个数位,数字是反向存储的,
* 即第一个结点表示最低位,最后一个结点表示最高位。求两个数的相加和,并且以链表形式返回。
* 解题思路
* 由于相加时都是对应的位相加,所以我采用递归的方法进行计算;先从个位算起,如果大于10,则取出余数,留在本位,如果大于10,则取整,給下十位位相加,进行计算,一次类推
*

*
* @param l1 第一个数
* @param l2 第二个数
* @return 结果
* @date 2017年2月4日 上午9:31:47
*/

public class LinkedNode {    int value;    LinkedNode next;    public LinkedNode(int value) {        this.value = value;    }
public class Solution {    public LinkedNode handler(LinkedNode l1,LinkedNode l2){        return helper(l1,l2,0);    }     public LinkedNode helper(LinkedNode l1,LinkedNode l2,int carry){        if (l1 == null && l2 == null) {            return carry == 0? null : new LinkedNode(carry);        }        if (l1 == null && l2 != null) {            l1 = new LinkedNode(0);        }        if (l1 != null && l2== null) {            l2 = new LinkedNode(0);        }        LinkedNode result = new LinkedNode(-1);        int sum = l1.value + l2.value + carry;        result.value = sum % 10;//取余用于本位使用        carry = sum / 10;//取整 用于进阶使用        result.next = helper(l1.next, l2.next, carry);//        int sum = l1.val + l2.val + carry;//        ListNode curr = new ListNode(sum % 10);//取余//        curr.next = helper(l1.next, l2.next, sum / 10);               return result;    }    public void outputResult(LinkedNode result){        if (result != null) {            System.out.print("-->"+result.value);            outputResult(result.next);        }    }
0 0
原创粉丝点击