当前位置:网站首页>华为面试题: 分糖果
华为面试题: 分糖果
2022-06-30 02:55:00 【四库全书的酷】
题目
小明从糖果盒中随意抓一把糖果
每次小明会取出一半的糖果分给同学们
当糖果不能平均分配时
小明可以从糖果盒中(假设盒中糖果足够)取出一个或放回一个糖果
小明至少需要多少次(取出放回和平均分配均记一次)能将手中糖果分至只剩一颗
输入描述:
抓取糖果数(小于1000000):15
输出描述:
最少分至一颗糖果的次数:5
示例1:
输入
15
输出
5
备注
解释:(1) 15+1=16;
(2) 16/2=8;
(3) 8/2=4;
(4) 4/2=2;
(5) 2/2=1;
代码
注意点:是统计取回和放进去的次数!!
#include<iostream>
using namespace std;
int main(){
int n;
cin >> n;
int count = 0;
for(int i = n; i != 1;i /= 2,count++){
if(i == 3){
cout << count+2 << endl;
return 0;
}
//如果能被2整除,就不容取出或者放回;
//如果不能被2整除,统一一下+1和-1后谁的最少!;这里使用了局部最优!!
if(i % 2 != 0){
if((i + 1)/2 % 2 == 0) i+=1;
else --i;
++count;
}
}
cout << count << endl;
return 0;
}
边栏推荐
- Precautions for purchasing wildcard SSL certificate
- Série de tutoriels cmake - 02 - génération de binaires à l'aide du Code cmake
- Cmake tutorial series -05- options and variables
- A quick look at the statistical data of 23 major cyber crimes from 2021 to 2022
- (graph theory) connected component (template) + strongly connected component (template)
- [oiclass] chess piece
- How do I enable assembly binding logging- How can I enable Assembly binding logging?
- Global and Chinese markets for wireless security in LTE networks 2022-2028: Research Report on technology, participants, trends, market size and share
- Intel hex, Motorola S-Record format detailed analysis
- Distributed file system fastdfs
猜你喜欢

发现mariadb数据库时间晚了12个小时

福利抽奖 | 开源企业级监控Zabbix6.0都有哪些亮点

Wechat applet page Jump and parameter transfer

Série de tutoriels cmake - 02 - génération de binaires à l'aide du Code cmake

2. 成功解决 BUG:Exception when publishing, ...[Failed to connect and initialize SSH connection...

IDEA 远程调试 Remote JVM Debug

IBM WebSphere channel connectivity setup and testing

Recursion frog jumping steps problem

Differences among digicert, SECTIONO and globalsign code signing certificates

Distributed file system fastdfs
随机推荐
Welfare lottery | what are the highlights of open source enterprise monitoring zabbix6.0
Tp6 framework integrates JWT for token authentication
Pytoch learning (II)
Multi card server usage
Add a custom button to jvxetable
2022 tool fitter (Advanced) and tool fitter (Advanced) certificate examination
Unity timeline data binding
Raii memory management
GTK interface programming (I): Environment Construction
oracle怎么设置密码复杂度及超时退出的功能
在php中字符串的概念是什么
Simulate activity startup mode in compose
Wechat applet +php to realize authorized login operation
怎样的外汇交易平台是有监管的,是安全的?
Raki's notes on reading paper: named entity recognition as dependency parsing
Global and Chinese market of wind energy equipment logistics 2022-2028: Research Report on technology, participants, trends, market size and share
模板参数包和函数参数包
Cmake tutorial series-03-dependency management
What should academic presentation /ppt do?
Recursion frog jumping steps problem