441. Arranging Coins

You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.

Given n, find the total number of full staircase rows that can be formed.

n is a non-negative integer and fits within the range of a 32-bit signed integer.

Example 1:

n = 5

The coins can form the following rows:
¤
¤ ¤
¤ ¤

Because the 3rd row is incomplete, we return 2.

 

Example 2:

n = 8

The coins can form the following rows:
¤
¤ ¤
¤ ¤ ¤
¤ ¤

Because the 4th row is incomplete, we return 3.

1+2+3...+k <= n 求k的最大值

C++(22ms):
 1 class Solution {
 2 public:
 3     int arrangeCoins(int n) {
 4         int left = 0 ;
 5         int right = n ;
 6         while(left <= right){
 7             int mid = left + (right - left) / 2 ;
 8             if (0.5 * (1+mid) * mid <= n)
 9                 left = mid + 1;
10             else
11                 right = mid - 1;
12         }
13         return left - 1 ;
14     }
15 };

 

 

 

java(61ms):

1 class Solution {
2     public int arrangeCoins(int n) {
3         return (int)((-1 + Math.sqrt(1 + 8 * (long)n)) / 2);
4     }
5 }

 

 
posted @ 2017-11-22 16:49  __Meng  阅读(159)  评论(0编辑  收藏  举报