当前位置:网站首页>华为面试题: 分糖果
华为面试题: 分糖果
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;
}
边栏推荐
- 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
- Unity3D UGUI强制刷新Layout(布局)组件
- O & M (21) make winpe startup USB flash disk
- NLP text summary: data set introduction and preprocessing [New York Times annotated corpus]
- FDA mail security solution
- prompt learning 一个空格引发的血案
- Jvxetable增加自定义按钮
- Time complexity analysis
猜你喜欢

2.8 【 weight of complete binary tree 】

How to prevent phishing emails? S/mime mail certificate

What is digicert smart seal?

Pytoch learning (II)

Some configuration details about servlet initial development

Software testing skills, JMeter stress testing tutorial, transaction controller of logic controller (25)

怎么利用Redis实现点赞功能

Study diary: February 15, 2022

Uniapp address translation latitude and longitude

CMake教程系列-02-使用cmake代碼生成二進制
随机推荐
Two methods of SSL certificate format conversion
How to modify and add fields when MySQL table data is large
How does native JS generate Jiugong lattice
自定义JvxeTable的按钮及备注下$set的用法
New edition of diazotization process in 2022 and analysis of diazotization process
怎么使用Vant实现数据分页和下拉加载
公司电脑强制休眠的3种解决方案
Servlet面试题
How can redis+aop customize annotations to achieve flow restriction
多卡服务器使用
Formal and actual parameters, value passing and address passing
微信小程序页面跳转以及参数传递
CMake教程系列-05-选项及变量
CMake教程系列-01-最小配置示例
Cmake tutorial series -04- compiling related functions
Global and Chinese market of wind energy equipment logistics 2022-2028: Research Report on technology, participants, trends, market size and share
外汇交易平台哪个好?有监管的资金就安全吗?
shell统计某个字符串最后一次出现的位置之前的所有字符串
How do I enable assembly binding logging- How can I enable Assembly binding logging?
[dry goods sharing] the latest WHQL logo certification application process