HELP!! can't figure out why my code is wrong


  • 0
    B
    public int nthUglyNumber(int n) {
        if(n-- == 1) return 1;
        int p2 = 1, p3 = 1, p5 = 1;
        int n2 = 2, n3 = 3, n5 = 5;
        int res = 0;
        for(int i = 0; i < n ;i++){
            int t2 = n2,t3=n3,t5=n5;
            res = min(n2,n3,n5);
            if(min(n2,n3,n5) == n2){
                n2 =2*(++p2);   
            }
            if(min(t2,t3,t5) == n3){
                n3  =3* (++p3); 
            }
            if(min(t2,t3,t5) == n5){
                n5  =5* (++p5); 
            }
        }
        return res;
    }
    public int min(int a, int b, int c){
        return Math.min(a,Math.min(b,c));
    }
    

    }


  • 0
    D

    (++p2) is wrong. the next num is 2*(next ugly num in the sequence);
    For example:
    in your code,the sequence of p2 is 1,2,3,4,5,6,7.However, the right sequence is 1,2,3,4,5,6,8 (7 is not here).


Log in to reply
 

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