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

LeetCode 441 Arranging Coins

时间:2016-11-01 13:38:02      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:for   cas   nal   while   return   com   ati   ber   ant   

Problem:

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.

Summary:

用n枚硬币摆成塔形,求可以摆成的完整的行数。

Analysis:

1.最简单的思路,依次减去递增的每行硬币数,直到n为非整数。

 1 class Solution {
 2 public:
 3     int arrangeCoins(int n) {
 4         int i = 0;
 5         while (n > 0) {
 6             i++;
 7             n -= i;
 8         }
 9         
10         return n == 0 ? i : i - 1;
11     }
12 };

 2. 解一元二次方程:x^2 + x = 2 * n 解得:x = sqrt(2 * n + 1 / 4) - 1 /2

但要注意在此处n为32位有符号整型数,2 * n后有可能溢出,故在代码中应做相应处理。

1 class Solution {
2 public:
3     int arrangeCoins(int n) {
4         return sqrt((long long)2 * n + 0.25) - 0.5;
5     }
6 };

 

LeetCode 441 Arranging Coins

标签:for   cas   nal   while   return   com   ati   ber   ant   

原文地址:http://www.cnblogs.com/VickyWang/p/6015456.html

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