当前位置:网站首页>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;
}
边栏推荐
- MATLAB skills (28) Fuzzy Comprehensive Evaluation
- [trio basic tutorial 16 from introduction to proficiency] UDP communication test supplement
- Let's briefly talk about the chips commonly used in mobile phones - OVP chips
- Management and use of DokuWiki (supplementary)
- Arduino operation stm32
- MATLAB小技巧(28)模糊綜合評價
- One question per day - replace spaces
- 關於線性穩壓器的五個設計細節
- [cloud native | learn kubernetes from scratch] III. kubernetes cluster management tool kubectl
- [trio basic from introduction to mastery tutorial 20] trio calculates the arc center and radius through three points of spatial arc
猜你喜欢

Sword finger offer 05 Replace spaces

DCDC circuit - function of bootstrap capacitor

Example 006: Fibonacci series

剑指 Offer 09. 用两个栈实现队列

Bluebridge cup internet of things basic graphic tutorial - GPIO input key control LD5 on and off

【NOI模拟赛】汁树(树形DP)

Arduino operation stm32

MATLAB小技巧(28)模糊综合评价

Daily question - input a date and output the day of the year

Array integration initialization (C language)
随机推荐
Soem EtherCAT source code analysis attachment 1 (establishment of communication operation environment)
[tutorial 15 of trio basic from introduction to proficiency] trio free serial communication
Tailq of linked list
MySQL MHA high availability cluster
STM32 virtualization environment of QEMU
Matlab tips (28) fuzzy comprehensive evaluation
Example 008: 99 multiplication table
Classic application of MOS transistor circuit design (1) -iic bidirectional level shift
Esphone retrofits old fans
One question per day - replace spaces
UE像素流,来颗“减肥药”吧!
MATLAB小技巧(28)模糊綜合評價
Go dependency injection -- Google open source library wire
Esp8266 interrupt configuration
Arduino+a4988 control stepper motor
QEMU STM32 vscode debugging environment configuration
STM32 single chip microcomputer - external interrupt
List of linked lists
Arduino burning program and Arduino burning bootloader
Example 007: copy data from one list to another list.