码迷,mamicode.com
首页 > 其他好文 > 详细

(Easy) Arranging Coins - LeetCode

时间:2019-08-29 18:41:33      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:Nging   col   nbsp   int   fail   issue   str   follow   can   

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

标签:Nging   col   nbsp   int   fail   issue   str   follow   can   

原文地址:https://www.cnblogs.com/codingyangmao/p/11431047.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!