LeetCode-Add Two Numbers
Description:
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation:
342 + 465 = 807.
题意:给定两个由整数组成的链表,链表的每个节点都带有一个[0,9]的数字,每个链表都表示一个数字,头结点为数字的低位,尾结点为高位,要求将两个链表表示的数字相加,并以链表的形式返回;
解法:其实,就是对链表的各个相应位置的数字相加,注意有进位的可能,以及两个链表的长度可能不一致、链表可能为空的可能;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode addResult = new ListNode(0);//头结点
ListNode addResultNext = addResult;//尾结点
int sum = 0;//两个数的和
int cf = 0;//进位标志
while(l1 != null || l2 != null){
int x = l1 == null ? 0 : l1.val;
int y = l2 == null ? 0 : l2.val;
sum = x + y + cf;
cf = sum / 10;
addResultNext.next = new ListNode(sum % 10);
addResultNext = addResultNext.next;
if(l1 != null) l1 = l1.next;
if(l2 != null) l2 = l2.next;
}
if(cf != 0){
addResultNext.next = new ListNode(cf);
}//最高位相加仍有进位
return
版权声明
本文仅代表作者观点,不代表博信信息网立场。