(Easy) Arranging Coins - LeetCode

Description:

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.
Accepted
76,246
Submissions
197,998

Solution:

First Attempt:

Time Limit Exceeded. 

 

 

class Solution {
    public int arrangeCoins(int n) {
        
        
        int sum = 0;
         int k  = 0;
        for(int i =1; sum<=n; i++){
            if(sum+i<=n){
                 sum = sum+i;
            }
           else{
               
               k = i;
               break;
           }
            
             
        }
            if((n-sum)==k){
                return k;
            }
        else return k-1;
    }
}

 

Second Attempt:

 

Using Formula, performs much better with the test cases, but still some failed.

 

 

The Issue lies in that 8* n if the type is int, it would cause overflow. 

we could transfer it to long before we multiply. 

thus it is a math problem. 

All test cases passed.

 

posted @ 2019-08-29 17:35  CodingYM  阅读(111)  评论(0编辑  收藏  举报