https://leetcode.com/problems/arranging-coins/description/
Solution 1. Subtract the s-th row from n each time.
int arrangeCoins(int n) {
int s = 0;
while(n>s) {
s++;
n -= s;
}
return s;
}
Solution 2. A full staircase with s rows and n coins has s(s+1) = 2*n.
Thus s = (-1 + sqrt(1+8*n)) / 2 = (-0.25 + sqrt(2*n + 0.25).
int arrangeCoins(int n) {
return floor(-0.5+sqrt((double)2*n+0.25));
}
No comments:
Post a Comment