(Easy) Arranging Coins - LeetCode

Posted codingyangmao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(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.

技术图片

 

以上是关于(Easy) Arranging Coins - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Arranging Coins

arranging-coins

441. Arranging Coins

441. Arranging Coins

[LeetCode] Arranging Coins 排列硬币

138.Arranging Coins