Problem:
You had a total of n coins so want to form in a staircase shape, where every K-th Row must had E xactly 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 = 5The coins can form the following rows:¤¤¤¤¤because the 3rd row is incomplete, we return 2.
Example 2:
n = 8The coins can form the following rows:¤¤¤¤¤¤¤¤because the 4th row is incomplete, we return 3.
Summary:
With n coins in a tower shape, the complete number of rows can be placed.
Analysis:
1. The simplest way of thinking, minus the increment of the number of coins per line, until n is a non-integer.
1 classSolution {2 Public:3 intArrangecoins (intN) {4 inti =0;5 while(N >0) {6i++;7N-=i;8 }9 Ten returnn = =0? I:I-1; One } A};
2. Solve the unary two-th equation: x^2 + x = 2 * N solution: x = sqrt (2 * n + 1/4)-1/2
But note that here n is a 32-bit signed integer number, 2 * n may overflow, so in the code should be handled accordingly.
1 class Solution {2public:3 int arrangecoins (int n) {4 return sqrt (long long) 2 0.25 0.5 ; 5 }6 };
Leetcode 441 Arranging Coins