It‘s strange that the code runs right in my IDE,OJ judge it's wrong


  • 0
    C

    package solution;

    public class Solution2 {
    public static ListNode addTwoNumbers(ListNode l1,ListNode l2){
    ListNode p=l1;
    int number1=0,number2=0,mul1=0,mul2=0,sum;

    	for(p = l1; p != null; p=p.next){
    		number1 = (int) (number1 + p.val*Math.pow(10,mul1));
    		mul1++;
    	}
    	for(p = l2; p != null; p=p.next){
    		number2 = (int) (number2 + p.val*Math.pow(10,mul2));
    		mul2++;
    	}
    	
    	int temp_len = (mul1>=mul2)?mul1:mul2;//两个数的最大长度
    	int len=temp_len;
    	sum = number1 +number2;
    	//根据sum求长度,要么为temp_len要么为temp_len+1
    	if(sum>=Math.pow(10, temp_len-1) && sum < Math.pow(10, temp_len))
    		len = temp_len;
    	else if(sum>=Math.pow(10, temp_len))
    		len = temp_len+1;
    	
    	//获取每一位数,构造链表节点 从低位开始赋值
    	ListNode l3 = new ListNode(0);
    	p=l3;
    
    	for(int i=1;i<=len;i++){
    		p.val =sum%10;
    		sum = sum/10;
    		if(sum>0){
    			ListNode nextNode = new ListNode(0);
    			nextNode.next=null;
    			p.next = nextNode;
    			p=p.next;
    		}
    	}
    	return l3;
    }
    public static void main(String[] args){
    	ListNode p,l;
    /*	ListNode l1 = new ListNode(2);
    	ListNode l2 = new ListNode(3);
    	ListNode l3 = new ListNode(4);
    	ListNode l4 = new ListNode(1);
    	ListNode l5 = new ListNode(5);
    	ListNode l6 = new ListNode(6);
    
    	l1.next=l2;
    	l2.next=l3;
    	l3.next=null;
    	//
    	l4.next=l5;
    	l5.next=l6;
    	l6.next=null;
    	*/
    	ListNode l0 = new ListNode(9);
    	ListNode l1 = new ListNode(1);
    	ListNode l2 = new ListNode(9);
    	ListNode l3 = new ListNode(9);
    	ListNode l4 = new ListNode(9);
    	ListNode l5 = new ListNode(9);
    	ListNode l6 = new ListNode(9);
    	ListNode l7 = new ListNode(9);
    	ListNode l8 = new ListNode(9);
    	ListNode l9 = new ListNode(9);
    	l1.next=l2;
    	l2.next=l3;
    	l3.next=l4;
    	l4.next=l5;
    	l5.next=l6;
    	l6.next=l7;
    	l7.next=l8;
    	l8.next=l9;
    	l9.next=null;
    	l0.next=null;
    	
    	l = addTwoNumbers(l0,l1);
    	for(p=l;p!=null;p=p.next)
    	System.out.println(p.val);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.