zoukankan      html  css  js  c++  java
  • 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;
    }
    
    }
    小球轨迹
  • 相关阅读:
    QGraphicsItem鼠标旋转控制研究
    QT场景视图父子关系图元打印研究
    QT绘制B样条曲线
    [转]localhost、127.0.0.1和0.0.0.0和本机IP的区别
    [转]C++ 堆栈溢出的原因以及可行的解决方法
    C++运算符重载学习总结
    关于C++中使用++it还是it++的问题
    [转]QT中的D指针与Q指针
    Python图像处理库:Pillow 初级教程
    STEP-MXO2开发板 [STEP FPGA开源社区]
  • 原文地址:https://www.cnblogs.com/importnew/p/4281359.html
Copyright © 2011-2022 走看看