• Leet Code add two number


    add two number

    题目要求:
    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

    public class ListNode {
        int val;
        ListNode next=null;
    
        ListNode(int x) {
            val = x;
            next = null;
        }
     }
    

    .

    public class Solution {
    
    public static void main(String[] args) {
    
        ListNode listNodeL1=new ListNode(1);
        ListNode listNodeL1_2=new ListNode(2);
        ListNode listNodeL1_3=new ListNode(3);
        listNodeL1.next=listNodeL1_2;
        listNodeL1_2.next=listNodeL1_3;
        listNodeL1_3.next=null;
    
        ListNode listNodeL2=new ListNode(1);
        ListNode listNodeL2_2=new ListNode(2);
        ListNode listNodeL2_3=new ListNode(3);
        listNodeL2.next=listNodeL2_2;
        listNodeL2_2.next=listNodeL2_3;
        listNodeL2_3.next=null;
        Solution solution = new Solution();
       ListNode rs= solution.addTwoNumbers(listNodeL1,listNodeL2);
        while (rs!=null){
            System.out.println(rs.val);
            rs=rs.next;
        }
    }
    
    
    
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode rs=new ListNode(0);
        ListNode cur=rs;
        int carry = 0;
        int i = 0;
        int j = 0;
        while (l1 != null || l2 != null) {
            if (l1 != null) {
                i = l1.val;
                l1=l1.next;
            }
            if (l2 != null) {
                j = l2.val;
                l2 = l2.next;
            }
            int sum = i + j + carry; //如果大于10 进位
    
            cur.next=new ListNode(sum%10); //创建一个新的节点
            cur=cur.next; //把下个节点和当前节点连起来
            carry=sum/10;//算进位
        }
        if(carry>0) cur.next=new ListNode(carry);
        return rs.next;
    }
    
    }
    小球轨迹
  • 相关阅读:
    mysql数据库小常识
    CSP.ac #61乘积求和
    CSP.ac #60
    CSP.ac低仿机器人(T1-1)
    题解:swj社会摇基础第一课
    题解:T103180 しろは的军训列队
    关 于 篮 球
    关 于 自 恋
    题解:T103342 Problem A. 最近公共祖先
    关 于 匀 变 速 直 线 运 动 的 推 论
  • 原文地址:https://www.cnblogs.com/importnew/p/4281359.html
Copyright © 2020-2023  润新知