#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.
Example:
Given n = 3.
At first, the three bulbs are [off, off, off].
After first round, the three bulbs are [on, on, on].
After second round, the three bulbs are [on, off, on].
After third round, the three bulbs are [on, off, off].
So you should return 1, because there is only one bulb is on.
分析:此题初始的时候,灯是熄灭的。然后第一次,对1的倍数的灯都执行操作,
第二次对2的倍数的灯都执行操作,..第n次对n的倍数的灯都执行操作,
问第n次操作结束后,亮着的灯的个数。
总结规律:对于第i盏灯,实际上就是求的i在1~n的可以整除的个数。
例如n=3时,2能够除以1,2都没有余数,实际灯2会被操作2次,初始为熄灭,
操作两次,仍然熄灭,所以只有整除的个数是奇数个的灯最后才会亮着。
发现:能被9整除的数是1,3,9共3个,25是1,5,15
也就是说只有某个数的开根号仍然为整数,该数才拥有奇数个除数,
灯才会亮着。
问题转化为:求n个数中,拥有开根号后仍然为整数的数字个数,即
1,4,9,16,25...,
答案为(int)sqrt(n)
输入:
0
1
3
4
100
输出:
0
1
1
2
10
关键:
1 总结规律:对于第i盏灯,实际上就是求的i在1~n的可以整除的个数。
例如n=3时,2能够除以1,2都没有余数,实际灯2会被操作2次,初始为熄灭,
操作两次,仍然熄灭,所以只有整除的个数是奇数个的灯最后才会亮着。
发现:能被9整除的数是1,3,9共3个,25是1,5,15
也就是说只有某个数的开根号仍然为整数,该数才拥有奇数个除数,
灯才会亮着。
问题转化为:求n个数中,拥有开根号后仍然为整数的数字个数,即
1,4,9,16,25...,
答案为(int)sqrt(n)
*/
class Solution {
public:
int bulbSwitch(int n) {
if(n <= 0)
{
return 0;
}
int result = (int)sqrt(n);
return result;
}
};
void print(vector<int>& result)
{
if(result.empty())
{
cout << "no result" << endl;
return;
}
int size = result.size();
for(int i = 0 ; i < size ; i++)
{
cout << result.at(i) << " " ;
}
cout << endl;
}
void process()
{
int num;
Solution solution;
while(cin >> num )
{
int result = solution.bulbSwitch(num);
cout << result << endl;
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
leecode 解题总结:319. Bulb Switcher
最新推荐文章于 2020-09-26 00:32:29 发布