Leetcode(2)两数相加

package com.leetcode.addtwonumbers;

/**
 * 题目:给出两个非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字.
 * 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 eg:输入:(2 -> 4
 * -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
 * 思考:每一位的和=进位+head1.val+head2.val。如果到最高位还有进位,则需要增加一个节点。
 * @author hexiaoli
 */
class ListNode {
	int val;
	ListNode next = null;

	public ListNode(int val) {
		this.val = val;
	}
}

public class Solution {

	public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		// 设置两个指针
		ListNode head1 = l1;
		ListNode head2 = l2;
		// 表示进位
		int isopsephy = 0;
		while (head1 != null) {
			// 如果两个链表长度不够需要补位
			if (head1.next == null && head2.next != null) {
				head1.next = new ListNode(0);
			}
			if (head2.next == null && head1.next != null) {
				head2.next = new ListNode(0);
			}
			// 相加
			int sum = isopsephy + head1.val + head2.val;
			// 表示进位
			isopsephy = sum / 10;
			// head1被重新赋值
			head1.val = (sum % 10);
			if (head1.next == null && head2.next == null && isopsephy != 0) {
				head1.next = new ListNode(isopsephy);
				break;
			}
			// 计算下一位
			head1 = head1.next;
			head2 = head2.next;
		}
		return l1;
	}

	public static void main(String[] args) {
		ListNode head1 = new ListNode(2);
		ListNode head11 = new ListNode(4);
		ListNode head12 = new ListNode(3);
		head1.next = head11;
		head11.next = head12;
		ListNode head2 = new ListNode(5);
		ListNode head21 = new ListNode(6);
		ListNode head22 = new ListNode(7);
		head2.next = head21;
		head21.next = head22;

		ListNode result = addTwoNumbers(head1, head2);
		while (result != null) {
			System.out.println(result.val);
			result = result.next;
		}

	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值