力扣-两数相加

package com.JackChen.leetCode.Day1;

import java.util.Scanner;

/**
 * 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
 * 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
 * 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
 * 示例:
 * 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
 * 输出:7 -> 0 -> 8
 * 原因:342 + 465 = 807
 * 
 * @author Jack Chen
 *
 */
public class AddTwoNumber {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner(System.in);
		while (scanner.hasNextLine()) {//键盘获取2个字符串以空格隔开
			String firstInput = scanner.nextLine();
			String secondInput = scanner.nextLine();
			//构建链表
			ListNode node1 = creatListNode(firstInput);
			ListNode node2 = creatListNode(secondInput);

            //打印链表
			print(addTwoNumbers(node1, node2));
		}
	}
	
	private static ListNode addTwoNumbers(ListNode node1, ListNode node2) {
		// TODO Auto-generated method stub
		
		ListNode node = new ListNode();//创建一个链表
		ListNode cur = node;//使用操作cur,因为操作完链表后,没有办法再次找到链表的头部
		
		int temp = 0;//进位
		while(node1 != null || node2 != null) {//只要有一个链表不为空,就需要计算
			int val1 = node1 == null ? 0 : node1.val;
			int val2 = node2 == null ? 0 : node2.val;
			
			int sum = val1 + val2 + temp;
			temp = sum/10;

			cur.next = new ListNode(sum%10);
			cur = cur.next;
			
			node1 = node1 == null ? null : node1.next;
			node2 = node2 == null ? null : node2.next;
		}

		if (temp != 0) {
			cur.next = new ListNode(temp);
		}
		return node.next;
	}

	private static ListNode creatListNode(String input) {
		// TODO Auto-generated method stub
		ListNode temp = new ListNode();
		ListNode node = temp;
		String[] arrays = input.split(" ");
		for (int i = 0; i < arrays.length; i++) {
			temp.next = new ListNode(Integer.parseInt(arrays[i]));
			temp = temp.next;
		}
		
		return node.next;
		
	}

	public static void print(ListNode node) {
		while(node != null) {
			System.out.print(node.val);
			node = node.next;
		}
	}
	public static class ListNode{
		int val;
		ListNode next;
		ListNode() {}
		ListNode(int val){
			this.val = val;
		}
		ListNode(int val, ListNode next){
			this.val = val;
			this.next = next;
		}
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值