leecode 解题总结:319. Bulb Switcher

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值