当前位置:网站首页>319. 灯泡开关
319. 灯泡开关
2022-07-05 08:31:00 【Mr Gao】
319. 灯泡开关
初始时有 n 个灯泡处于关闭状态。第一轮,你将会打开所有灯泡。接下来的第二轮,你将会每两个灯泡关闭第二个。
第三轮,你每三个灯泡就切换第三个灯泡的开关(即,打开变关闭,关闭变打开)。第 i 轮,你每 i 个灯泡就切换第 i 个灯泡的开关。直到第 n 轮,你只需要切换最后一个灯泡的开关。
找出并返回 n 轮后有多少个亮着的灯泡。
示例 1:
输入:n = 3
输出:1
解释:
初始时, 灯泡状态 [关闭, 关闭, 关闭].
第一轮后, 灯泡状态 [开启, 开启, 开启].
第二轮后, 灯泡状态 [开启, 关闭, 开启].
第三轮后, 灯泡状态 [开启, 关闭, 关闭].
你应该返回 1,因为只有一个灯泡还亮着。
示例 2:
输入:n = 0
输出:0
示例 3:
输入:n = 1
输出:1
这里灯泡是否关闭和他的约数个数有关:
常规解题代码如下:
int f(int n){
int count=1;
int i;
for(i=2;i<=n/2;i++){
if(n%i==0){
count++;
}
}
return count;
}
int bulbSwitch(int n){
int i;
if(n==0){
return 0;
}
int count=1;
for(i=2;i<=n;i++){
int c=f(i);
// printf("%d ",c);
if(c%2==0){
count++;
}
}
return count;
}
下面还由一种非常棒的技巧解法:
int bulbSwitch(int n){
int i;
if(n==0){
return 0;
}
int count=1;
for(i=2;i<=n;i++){
if(i*i>n){
return i-1;
}
}
return count;
}
边栏推荐
- How to write cover letter?
- 实例006:斐波那契数列
- STM32 virtualization environment of QEMU
- Buildroot system for making raspberry pie cm3
- Several important parameters of LDO circuit design and type selection
- Imx6ull bare metal development learning 2- use C language to light LED indicator
- [NAS1](2021CVPR)AttentiveNAS: Improving Neural Architecture Search via Attentive Sampling (未完)
- Detailed explanation of SQL server stored procedures
- Compilation warning solution sorting in Quartus II
- Management and use of DokuWiki (supplementary)
猜你喜欢
Example 009: pause output for one second
Example 008: 99 multiplication table
Example 004: for the day of the day, enter a day of a month of a year to judge the day of the year?
MHA High available Cluster for MySQL
L298N module use
[trio basic from introduction to mastery tutorial XIV] trio realizes unit axis multi-color code capture
NTC thermistor application - temperature measurement
Brief discussion on Buck buck circuit
STM32---IIC
Bluebridge cup internet of things competition basic graphic tutorial - clock selection
随机推荐
Naming rules for FreeRTOS
Example 010: time to show
Sizeof (function name) =?
STM32 single chip microcomputer - bit band operation
STM32 summary (HAL Library) - DHT11 temperature sensor (intelligent safety assisted driving system)
What are the test items of power battery ul2580
STM32 single chip microcomputer - external interrupt
Old Wang's esp8266 and old Wu's ws2818 light strip
STM32 --- configuration of external interrupt
[cloud native | learn kubernetes from scratch] III. kubernetes cluster management tool kubectl
Classic application of MOS transistor circuit design (1) -iic bidirectional level shift
[three tier architecture]
MATLAB小技巧(28)模糊綜合評價
[trio basic tutorial 16 from introduction to proficiency] UDP communication test supplement
Daily question - input a date and output the day of the year
2020-05-21
Talk about the function of magnetic beads in circuits
Stablq of linked list
UE像素流,来颗“减肥药”吧!
每日一题——输入一个日期,输出它是该年的第几天