LeetCode-2-算法-两数相加(中等)链表

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

审题:

思考:

解题:

/*
	 * 将当前结点初始化为返回列表的哑结点。
                    将进位 carry 初始化为 0。
                   将 p 和 q分别初始化为列表 l1 和 l2 的头部。
                   遍历列表 l1 和 l2 直至到达它们的尾端。
                   将 x 设为结点 p 的值。如果 p 已经到达 l1 的末尾,则将其值设置为 0。
                   将 y 设为结点 q 的值。如果 q 已经到达 l2 的末尾,则将其值设置为 0。
                   设定 sum = x + y + carry。
                   更新进位的值,carry = sum / 10。
                   创建一个数值为 (sum \bmod 10) 的新结点,并将其设置为当前结点的下一个结点,然后将当前结点前进到下一个结点。
                   同时,将 p 和 q 前进到下一个结点。
                   检查 carry = 1是否成立,如果成立,则向返回列表追加一个含有数字 1 的新结点。
                   返回哑结点的下一个结点。
	 * 
	 * 
	 */
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		ListNode dummyHead = new ListNode(0);
		ListNode p = l1;
		ListNode q = l2;
		//结果链表
		ListNode curr = dummyHead;
		//进位
		int carry = 0;
		while (p != null || q != null) {
			//三目运算,如果为真取第一个结果,假取第二个结果。
			int x = (p != null) ? p.val : 0;
			int y = (q != null) ? q.val : 0;
			int sum = carry + x + y;
			//更新进位值,如果和超过10,进位就是1,除10取整。
			carry = sum / 10;
			curr.next = new ListNode(sum % 10);
			curr = curr.next;
			if (p != null) {
				p = p.next;
			}
			if (q != null) {
				q = q.next;
			}
		}
		if (carry > 0) {
			curr.next = new ListNode(carry);
		}
		return dummyHead.next;
	}

完整解答:

package com.sunjianlong.july.LeetCode.medium;

/*
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
关于链表的知识。
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
//定义链表
class ListNode {
	int val;
	ListNode next;

	ListNode(int x) {
		val = x;
	}
}

class Solution_21 {
	/*
	 * 将当前结点初始化为返回列表的哑结点。
                    将进位 carry 初始化为 0。
                   将 p 和 q分别初始化为列表 l1 和 l2 的头部。
                   遍历列表 l1 和 l2 直至到达它们的尾端。
                   将 x 设为结点 p 的值。如果 p 已经到达 l1 的末尾,则将其值设置为 0。
                   将 y 设为结点 q 的值。如果 q 已经到达 l2 的末尾,则将其值设置为 0。
                   设定 sum = x + y + carry。
                   更新进位的值,carry = sum / 10。
                   创建一个数值为 (sum \bmod 10) 的新结点,并将其设置为当前结点的下一个结点,然后将当前结点前进到下一个结点。
                   同时,将 p 和 q 前进到下一个结点。
                   检查 carry = 1是否成立,如果成立,则向返回列表追加一个含有数字 1 的新结点。
                   返回哑结点的下一个结点。
	 * 
	 * 
	 */
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		ListNode dummyHead = new ListNode(0);
		ListNode p = l1;
		ListNode q = l2;
		//结果链表
		ListNode curr = dummyHead;
		//进位
		int carry = 0;
		while (p != null || q != null) {
			//三目运算,如果为真取第一个结果,假取第二个结果。
			int x = (p != null) ? p.val : 0;
			int y = (q != null) ? q.val : 0;
			int sum = carry + x + y;
			//更新进位值,如果和超过10,进位就是1,除10取整。
			carry = sum / 10;
			curr.next = new ListNode(sum % 10);
			curr = curr.next;
			if (p != null) {
				p = p.next;
			}
			if (q != null) {
				q = q.next;
			}
		}
		if (carry > 0) {
			curr.next = new ListNode(carry);
		}
		return dummyHead.next;
	}

	public int[] addTwoNumbersbyInt(int[] l1, int[] l2) {
		int[] add ;
		if(l2.length >= l1.length) {
			add =new int[l2.length];
		}else {
			add =new int[l1.length];
		}
		int carry = 0;
		int i = 0;
		for (i = 0; i < l1.length || i < l2.length; i++) {
			int a = (i < l1.length) ? l1[i] : 0;
			int b = (i < l2.length) ? l2[i] : 0;
			int sum = carry + a + b;
			carry = sum / 10;
			add[i] = (sum % 10);
		}
		if (carry > 0) {
			//动态的增加数组的长度
			add=Arrays.copyOf(add, add.length+1);
			add[i] = 1;
		}

		return add;
	}
}

public class AddTwoNumbers_2 {
	// 将输入的String转换为IntegerArray
	public static int[] stringToIntegerArray(String input) {
		// 删除输入两端的空格
		input = input.trim();
		// 去除[] 删除两端的中括号
		input = input.substring(1, input.length() - 1);
		// 判断输入的[]是否为空,如果为空,返回空数组
		if (input.length() == 0) {
			return new int[0];
		}
		// 将字符串按照,分割成字符串数组
		String[] parts = input.split(",");
		// 新建int[],长度和字符串数组一致
		int[] output = new int[parts.length];
		// 遍历字符串数组,将字符串数组转换为int[]数组;
		for (int i = 0; i < output.length; i++) {
			// 取出字符串数组的中每一项并且删除前后空格
			String part = parts[i].trim();
			// 将String转换为int写入output数组
			output[i] = Integer.parseInt(part);
		}
		return output;
	}

	public static ListNode stringToListNode(String input) {
		// 将输入的字符串转换为int数组
		// Generate array from the input
		int[] nodeValues = stringToIntegerArray(input);

		// Now convert that list into linked list
		ListNode dummyRoot = new ListNode(0);
		ListNode ptr = dummyRoot;
		for (int item : nodeValues) {
			ptr.next = new ListNode(item);
			ptr = ptr.next;
		}
		return dummyRoot.next;
	}

	public static String integerArrayToString(int[] nums, int length) {
		if (length == 0) {
			return "[]";
		}

		String result = "";
		for (int index = 0; index < length; index++) {
			int number = nums[index];
			result += Integer.toString(number) + ",";
		}
		return "[" + result.substring(0, result.length() - 1) + "]";
	}
	
	public static String ListNodeToString(ListNode node) {
		if (node == null) {
			return "[]";
		}
		String result = "";
		while (node != null) {
			result += Integer.toString(node.val) + ",";
			node = node.next;
		}
		return "[" + result.substring(0, result.length() - 1) + "]";
	}
	/*
	 * public static void main(String[] args) { BufferedReader in = new
	 * BufferedReader(new InputStreamReader(System.in)); String line; try { while
	 * ((line = in.readLine()) != null) { ListNode l1 = stringToListNode(line); //
	 * 读取文本行 line = in.readLine(); ListNode l2 = stringToListNode(line);
	 * 
	 * ListNode ret = new Solution_21().addTwoNumbers(l1, l2);
	 * 
	 * String out = ListNodeToString(ret);
	 * 
	 * System.out.print(out); } } catch (IOException e) { // TODO Auto-generated
	 * catch block e.printStackTrace(); } }
	 */

	// 整数数组的操作方法

	public static void main(String[] args) {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String line;
		try {
			while ((line = in.readLine()) != null) {
				int[] l1 = stringToIntegerArray(line);
				line = in.readLine();
				int[] l2 = stringToIntegerArray(line);

				int[] ret = new Solution_21().addTwoNumbersbyInt(l1, l2);

				String out = integerArrayToString(ret, ret.length);
				
				System.out.print(out);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

知识点:

发布了118 篇原创文章 · 获赞 2 · 访问量 4886

猜你喜欢

转载自blog.csdn.net/Hello_JavaScript/article/details/104428938