zoukankan      html  css  js  c++  java
  • 2.5---链表来进行加法,链式A+B(CC150)

    这里是用了自己的方法,和书本不一样。

    import java.util.HashSet;
    import java.util.Set;
    
    
    
    class ListNode{
        int val;
        ListNode next;
        ListNode(int x){
            val = x;
        }
    }
    
    public class Solution{
    
        public static void main(String[] args){
            ListNode head = new ListNode(3);
            head.val = 3;
            ListNode node = new ListNode(1);
            node.val = 1;
            head.next = node;
            ListNode tmp = head;
            while(tmp != null){
                System.out.println(tmp.val);
                tmp = tmp.next;
            }
            
            System.out.println("delete");
            tmp = sum(null,null);
        
            while(tmp != null){
    
                System.out.println(tmp.val);
                tmp = tmp.next;
            }
            
            
        }
    
        public static ListNode sum (ListNode head1, ListNode head2){
            if(head1 == null ) return head2;
            if(head2 == null) return head1;
            
            int n1 = 0;
            int n2 = 0;
            int sum = 0;
            int flag = 0;
            while(head1 != null){
                n1 += head1.val * Math.pow(10, flag++);
                head1 = head1.next;
            }
            flag = 0;
            while(head2 != null){
                n2 += head2.val * Math.pow(10, flag++);
                head2 = head2.next;
            }
            
            sum = n1 + n2;
            System.out.println("sum = " + sum);
            int digit = sum % 10;
            ListNode head = new ListNode(digit);
            ListNode res = head;
            sum /= 10;
            while(sum != 0){
                digit = sum % 10;
                ListNode n = new ListNode(digit);
                head.next = n;
                head = head.next;
                sum /= 10;
            }
            return res;
        }
    }
  • 相关阅读:
    NFS安装配置与客户端的优化参数
    DELL硬件防火墙配置
    华为交换机命令
    lvs + keepalive的安装配置
    IPVS 的管理
    奇葩的404报错
    js 程序出发事件
    jvm 参数
    策略模式代替大量的if else
    采购订单行类型校验规则
  • 原文地址:https://www.cnblogs.com/yueyebigdata/p/5055636.html
Copyright © 2011-2022 走看看