classSolution: defarrangeCoins(self, n: int) -> int: left, right = 1, n while left < right: mid = (left + right + 1) // 2 if mid * (mid + 1) <= 2 * n: left = mid else: right = mid - 1 return left
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { publicintarrangeCoins(int n) { intleft=1, right = n; while (left < right) { intmid= (right - left + 1) / 2 + left; if ((long) mid * (mid + 1) <= (long) 2 * n) { left = mid; } else { right = mid - 1; } } return left; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicclassSolution { publicintArrangeCoins(int n) { int left = 1, right = n; while (left < right) { int mid = (right - left + 1) / 2 + left; if ((long) mid * (mid + 1) <= (long) 2 * n) { left = mid; } else { right = mid - 1; } } return left; } }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12
var arrangeCoins = function(n) { let left = 1, right = n; while (left < right) { const mid = Math.floor((right - left + 1) / 2) + left; if (mid * (mid + 1) <= 2 * n) { left = mid; } else { right = mid - 1; } } return left; };
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: intarrangeCoins(int n){ int left = 1, right = n; while (left < right) { int mid = (right - left + 1) / 2 + left; if ((longlong) mid * (mid + 1) <= (longlong) 2 * n) { left = mid; } else { right = mid - 1; } } return left; } };