easy java method with explanation


  • 0

    I use two methods: lastRemaining(), which is count from left to right, and backLastRemaing(), which is count from right to left, then we have
    lastRemaining(n)=backLastRemaining(n/2) whatever n is.
    backLastRemaining(n)=2lastRemaining(n/2), if n is odd,
    backLastRemaining(n)=2
    lastRemaining(n/2)-1, if n is even.

        public int lastRemaining(int n)
        {
            if(n==1)
                return 1;
            return 2*backLastRemaining(n/2);
        }
        public int backLastRemaining(int n)
        {
            if(n==1)
                return 1;
            if(n%2==0)
                return 2*lastRemaining(n/2)-1;
            return 2*lastRemaining(n/2);
        }
    

  • 0
    N

    @tony0055 said in easy java method with explanation:

    lastRemaining(n)=backLastRemaining(n/2) whatever n is.

    I think you meant lastRemaining = 2 * backLastRemaining(n/2). Thanks for the solution!


  • 0

    @nlavee yes, you're right


Log in to reply
 

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