leecode 解题总结:319. Bulb Switcher

来源:互联网 发布:劲舞团网吧合作软件 编辑:程序博客网 时间:2024/06/07 04:11
#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)输入:0134100输出:011210关键: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;}

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 苹果5s像素不好怎么办 华为mate边缘有缝怎么办 华为mate8边缘有缝怎么办 手机系统占用运行内存大怎么办 安卓手机储存空间不足怎么办 手机显示系统空间不足怎么办 联系人存储已停止运行怎么办 荣耀note8听筒声音小怎么办 红米4x内存不足怎么办 安卓电视内存小怎么办 红米手机运行内存不足怎么办 红米手机存储空间不足怎么办 华为手机储存空间不足怎么办 大麦机顶盒遥控器丢了怎么办 大麦盒子总自动加软件怎么办 小米手机玩王者荣耀卡怎么办 荣耀8青春版信号差怎么办 华为mate8电池不耐用怎么办 华为4x内存小怎么办 发现手机被用过怎么办 华为p8手机声音小怎么办 手机指纹解锁密码忘了怎么办 华为p10黑色掉漆怎么办 金立手机导航信号弱怎么办 手机导航时gps信号弱怎么办 三星手机导航gps信号弱怎么办 小米5导航信号弱怎么办 华为手机导航gps信号弱怎么办 手机屏玻璃裂了怎么办 oppo音量键坏了怎么办 魅蓝手机屏幕碎了怎么办 手机钢化膜边缘有气泡怎么办 手机贴钢化膜边缘有气泡怎么办 苹果手机钢化膜边缘有气泡怎么办 手机膜里的水泡怎么办 膜贴好了有气泡怎么办 后档玻璃膜气泡怎么办 贴膜里面有灰尘怎么办 贴膜边缘不粘怎么办 贴膜时候的气泡怎么办 贴手机膜起泡了怎么办