Java solution using binary search


  • 0
    L
        public int arrangeCoins(int n) {
            //find the first val that is not equal to self.
            int s=1;
            int e=n;
            while(e>=s) {
                int p =(e-s)/2+s;
                int diff = compareCoins(p,n);
                if(diff==0) {
                    return p;
                }
                else if(diff>0) {
                    e = p-1;
                }
                else {
                    s=p+1;
                }
            }
            return e;
        }
       
        private int compareCoins(int p, int n) {
            double sum = (double)p*(p+1)/2.0f;
            if(sum-n==0) {
                return 0;
            }
            return sum>n?1:-1;
        }
    

Log in to reply
 

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