Title Address: https://leetcode.com/problems/arranging-coins/description/
You has a total of n coins so want to form in a staircase shape, where every k-th row must has 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.
Two methods
Method One:
Class Solution {public
int arrangecoins (int n) {
long lo = 1, hi = n;//lo and hi are defined as long purely to facilitate mid assignment, int range enough
long Mid;
if (n = = 0) return 0;
while (Hi-lo > 1) {
mid = (lo + hi) >>> 1;//Here mid is going to define a long, although there is no problem with mid because of the addition overflow, but the following mid* (1+mid) >> ; >1 this expression defaults to int, there may be a multiplication overflow, far beyond the int range, the high-level portion of the binary is truncated, resulting in an error.
Long sum = Mid * (1 + mid) >>> 1;//sum must be long because int takes value to 2147483647 there is a step to get the 1297036691877396480
if (Sum > N) {
hi = mid;
} else {
lo = mid;
}
}
return (int) lo;
}
}
If you think Mid= (Lo+hi) >>>1 not good understanding, then change Mid=lo + ((hi-lo) >>1) bar, because lo in the int range, hi in the int range, Hi-lo also in the int range, and lo+ (Hi-lo) >>1 is less than hi, so it is also an int range. About why >>>1 better can read my other blog: https://blog.csdn.net/qq_34115899/article/details/79859973
But >>>1 can only solve the problem of additive overflow, almost not solve the multiplication overflow problem (unless there is a coincidence like multiplying by 2 and then >>>1, the high data is truncated, not saved), the solution is to choose a larger data type to handle the multiplication overflow problem.
Method Two:
It is easy to think of a mathematical method directly
x* (1+x)/2≤n
x+x2≤2n
We're going to use formula here.
4x+ 4x2≤4*2*n
(2x+1) 2-1≤8n
2x+1≤
X≤
Write code:
Class Solution {public
int arrangecoins (int n) {
Double t = 8.0 * n + 1;//cannot be written as 8*n+1, this expression is the default int and may result in an error in the results of an int range , so instead of 8.0, the expression becomes a double
return (int) ((math.sqrt (t)-1)/2);
}
}
============================= I am a slow-witted programmer ==========================