441. Arranging Coins
Il testo del problema è tradotto dal russo per la lingua selezionata. Il codice resta invariato.
У вас есть n монет, и вы хотите построить лестницу из этих монет. Лестница состоит из k рядов, где i-й ряд содержит ровно i монет. Последний ряд лестницы может быть неполным.
given intero n, return количество полных рядов лестницы, которые вы сможете построить.
Esempio:
Input: n = 5
Output: 2
Explanation: Because the 3rd row is incomplete, we return 2.
C# soluzione
abbinato/originalepublic class Solution {
public int ArrangeCoins(int n) {
return (int)(Math.Sqrt(2 * (long)n + 0.25) - 0.5);
}
}
C++ soluzione
bozza automatica, rivedere prima dell'invio#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public int ArrangeCoins(int n) {
return (int)(Math.Sqrt(2 * (long)n + 0.25) - 0.5);
}
}
Java soluzione
abbinato/originaleclass Solution {
public int arrangeCoins(int n) {
return (int)(Math.sqrt(2 * (long)n + 0.25) - 0.5);
}
}
JavaScript soluzione
abbinato/originalevar arrangeCoins = function(n) {
return Math.floor(Math.sqrt(2 * n + 0.25) - 0.5);
};
Python soluzione
abbinato/originaleclass Solution:
def arrangeCoins(self, n: int) -> int:
return int((2 * n + 0.25)**0.5 - 0.5)
Go soluzione
abbinato/originaleimport "math"
func arrangeCoins(n int) int {
return int(math.Sqrt(float64(2 * n) + 0.25) - 0.5)
}
Algorithm
Если мы глубже посмотрим на формулу задачи, мы можем решить её с помощью математики, без использования итераций.
Напомним, что Testo задачи можно выразить следующим образом: k(k + 1) ≤ 2N.
Это можно решить методом выделения полного квадрата, (k + 1/2)² - 1/4 ≤ 2N. Что приводит к следующему ответу: k = [sqrt(2N + 1/4) - 1/2].
😎
Vacancies for this task
offerte attive with overlapping task tags are mostrati.
Non ci sono ancora offerte attive.