Leetcode_Add Two Numbers

32 篇文章 0 订阅

Add Two Numbers

 

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

已下是java实现:

1、已知下列ListNode的数据结构

 public static class ListNode {
	     int val;
	     ListNode next;
	     ListNode(int x) { val = x; }
	 }
2、方法如下:

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		int add = 0;//存储进位
		int res = 0;//存储每一位相加的结果
		ListNode ln = new ListNode(0);
		ListNode key = ln;//key是当前节点
		while(l1!=null && l2!=null){//处理l1、l2都不为空的情况
			res = l1.val+l2.val+add;
			if(res>9){
				add=1;
				res=res-10;
			}
			else{
				add=0;
			}
			ListNode temp = new ListNode(res);
			key.next=temp;
			key=temp;
			l1=l1.next;
			l2=l2.next;
		}
		if(l1!=null){//处理只剩l1的情况
			while(l1!=null){
				res = l1.val+add;
				if(res>9){
					add=1;
					res=res-10;
				}
				else{
					add=0;
				}
				ListNode temp = new ListNode(res);
				key.next=temp;
				key=temp;
				l1=l1.next;
			}
		}
		else if(l2!=null){//处理只剩l2的情况
			while(l2!=null){
				res = l2.val+add;
				if(res>9){
					add=1;
					res=res-10;
				}
				else{
					add=0;
				}
				ListNode temp = new ListNode(res);
				key.next=temp;
				key=temp;
				l2=l2.next;
			}
		}
		if(add==1){//处理最后一位有进位的情况
			ListNode temp = new ListNode(1);
			key.next=temp;
			key=temp;
		}
		
		
		return ln.next;   
    }


3、写一个测试主方法

public static void main(String[] args) {

		ListNode l1 = new ListNode(2) ;
		l1.next=new ListNode(8);
		ListNode l2 = new ListNode(5) ;
		l2.next=new ListNode(9);
		l2.next.next=new ListNode(9);
		
		ListNode ln =addTwoNumbers(l1,l2);
		while(ln!=null)
		{
			System.out.println(ln.val+"------");
			ln=ln.next;
		}

	}


4、相当于

Input: (2 -> 8) + (5 -> 9 -> 9)
Output: 7 -> 7 -> 0- > 1

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值