Why this solution cannot pass


  • 0
    N

    just the last testcase can not pass,but the result is right,can someone help me?

     public static String largestNumber(int[] nums) {
        StringBuffer re=new StringBuffer();
        for(int i=0;i<nums.length;i++)
        {
        	int temp=i;
        	
        	for(int j=i+1;j<nums.length;j++)
        	{
        		  	temp=compareInt(nums[temp],nums[j],temp,j);
        		  	
        	}
    
        	re=re.append(nums[temp]);
        	int temp1=0;
        	temp1=nums[temp];
        	nums[temp]=nums[i];
        	nums[i]=nums[temp];
        	
        }
        if(re.charAt(0)=='0') return "0";
        return re.toString();
    }  
    public static int compareInt(int i,int j,int slice1,int slice2)
    {
    	int len1=String.valueOf(i).length();
    	int len2=String.valueOf(j).length();
    	String s=String.valueOf(i);
    	String t=String.valueOf(j);
    	int len=(len1>len2)?len1:len2;
    	for(int p=0;p<len;p++)
    	{
    		char m=(p>len1-1)?s.charAt(0):s.charAt(p);
    		char n=(p>len2-1)?t.charAt(0):t.charAt(p);
    		if(m>n) return slice1;
    		if(m<n) return slice2;		
    	}
    	return len1>len2?slice2:slice1;
    	
    }

  • 0

    but the result is right

    No it isn't. It's just similar.


  • 0
    M

    Looks like the problem in your code here:

        char m=(p>len1-1)?s.charAt(0):s.charAt(p);
        char n=(p>len2-1)?t.charAt(0):t.charAt(p);
    

    You always filling up lowest string with first character (charAt(0)), which is not correct. You should add chars sequential from beginning:
    f.e. compare 12312 and 123 in your code become: 12312 and 12311.


Log in to reply
 

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