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
- leecode 解题总结:319. Bulb Switcher
- 319. Bulb Switcher解题报告
- [leetcode] 319. Bulb Switcher 解题报告
- LeetCode 319. Bulb Switcher 解题报告
- [Leetcode] 319. Bulb Switcher 解题报告
- LeetCode---Bulb Switcher解题分析
- 319. Bulb Switcher && 672. Bulb Switcher II
- [leetcode] 319. Bulb Switcher
- 319. Bulb Switcher
- leetcode 319. Bulb Switcher
- 319. Bulb Switcher LeetCode
- LeetCode 319. Bulb Switcher
- 319. Bulb Switcher
- 319. Bulb Switcher
- 319. Bulb Switcher
- LeetCode *** 319. Bulb Switcher
- [leetcode]319. Bulb Switcher
- 319. Bulb Switcher
- 设计模式之(适配器模式)
- 【LeetCode 358】 Rearrange String k Distance Apart
- ES6 正则扩展
- maven+spring 遇到No mapping found for HTTP request with URI的问题
- Paragon ntfs for mac 15与Tuxera ntfs for mac2016.1哪个更好用
- leecode 解题总结:319. Bulb Switcher
- PAT甲级1041. Be Unique (20)
- SQL中create table语句创建数据表
- el表达式输出集合,集合中有对象,对象里还有对象属性
- log4j2基础篇(1)
- 用matlab批量新建和删除文件夹
- 使用NativeLibCompression极致压缩APK文件大小
- 分享 library 到 bintray jcenter代码库
- 别了——我的2016!