319. Bulb Switcher

LeetCode medium original: C# #csharp #leetcode #math #medium #string
Văn bản bài toán được dịch từ tiếng Nga theo ngôn ngữ giao diện. Mã không thay đổi.

Есть n лампочек, которые изначально выключены. Сначала вы включаете все лампочки, затем выключаете каждую вторую лампочку.

На третьем раунде вы переключаете каждую третью лампочку (включаете, если она выключена, или выключаете, если она включена). На i-ом раунде вы переключаете каждую i-ую лампочку. На n-ом раунде вы переключаете только последнюю лампочку.

return количество лампочек, которые будут включены после n раундов.

Ví dụ

Input: n = 3

Output: 1

Explanation: At first, the three bulbs are [off, off, off].

After the first round, the three bulbs are [on, on, on].

After the second round, the three bulbs are [on, off, on].

After the third round, the three bulbs are [on, off, off].

So you should return 1 because there is only one bulb is on.

Explanation: The two words can be "abcw", "xtfn".

C# lời giải

đã khớp/gốc
public class Solution {
    public int BulbSwitch(int n) {
        return (int) Math.Sqrt(n);
    }
}

C++ lời giải

bản nháp tự động, xem lại trước khi gửi
#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 BulbSwitch(int n) {
        return (int) Math.Sqrt(n);
    }
}

Java lời giải

đã khớp/gốc
class Solution {
    public int bulbSwitch(int n) {
        return (int) Math.sqrt(n);
    }
}

JavaScript lời giải

đã khớp/gốc
var bulbSwitch = function(n) {
    return Math.floor(Math.sqrt(n));
};

Python lời giải

đã khớp/gốc
class Solution:
    def bulbSwitch(self, n: int) -> int:
        return int(n ** 0.5)

Go lời giải

đã khớp/gốc
import "math"

func bulbSwitch(n int) int {
    return int(math.Sqrt(float64(n)))
}

Algorithm

Инициализация

Лампочка остается включенной, если она переключалась нечетное количество раз. Лампочка будет переключаться на каждом делителе её номера.

Định nghĩa состояния лампочки

Лампочка останется включенной только в том случае, если у нее нечетное количество делителей, что возможно только для квадратных чисел.

Подсчет включенных лампочек

Количество лампочек, которые будут включены после n раундов.

😎

Vacancies for this task

việc làm đang hoạt động with overlapping task tags are đã hiển thị.

Tất cả việc làm
Chưa có việc làm đang hoạt động.