441. Arranging Coins
Le texte du problème est traduit du russe pour la langue sélectionnée. Le code reste inchangé.
У вас есть n монет, и вы хотите построить лестницу из этих монет. Лестница состоит из k рядов, где i-й ряд содержит ровно i монет. Последний ряд лестницы может быть неполным.
given entier n, return количество полных рядов лестницы, которые вы сможете построить.
Exemple:
Input: n = 5
Output: 2
Explanation: Because the 3rd row is incomplete, we return 2.
C# solution
correspondant/originalpublic class Solution {
public int ArrangeCoins(int n) {
return (int)(Math.Sqrt(2 * (long)n + 0.25) - 0.5);
}
}
C++ solution
brouillon automatique, à relire avant soumission#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 solution
correspondant/originalclass Solution {
public int arrangeCoins(int n) {
return (int)(Math.sqrt(2 * (long)n + 0.25) - 0.5);
}
}
JavaScript solution
correspondant/originalvar arrangeCoins = function(n) {
return Math.floor(Math.sqrt(2 * n + 0.25) - 0.5);
};
Python solution
correspondant/originalclass Solution:
def arrangeCoins(self, n: int) -> int:
return int((2 * n + 0.25)**0.5 - 0.5)
Go solution
correspondant/originalimport "math"
func arrangeCoins(n int) int {
return int(math.Sqrt(float64(2 * n) + 0.25) - 0.5)
}
Algorithm
Если мы глубже посмотрим на формулу задачи, мы можем решить её с помощью математики, без использования итераций.
Напомним, что Énoncé задачи можно выразить следующим образом: k(k + 1) ≤ 2N.
Это можно решить методом выделения полного квадрата, (k + 1/2)² - 1/4 ≤ 2N. Что приводит к следующему ответу: k = [sqrt(2N + 1/4) - 1/2].
😎
Vacancies for this task
offres actives with overlapping task tags are affichés.
Il n'y a pas encore d'offres actives.