《Cracking the Coding Interview》——第6章:智力题——题目1

本文介绍了一个有趣的数学问题:如何仅通过一次称重从20瓶外观完全相同的药中找出唯一一瓶药片重量不同的瓶子。文章提供了一种巧妙的解决方案,并通过伪代码的形式进行了说明。

2014-03-19 06:40

题目:有20瓶药,其中19瓶装的都是1.0克的药片,只有1瓶装了1.1克的药。给你一个能称出具体克数的电子秤,只允许你称一次,怎么找出那瓶不一样的?

解法:如果药片管够,从每个瓶子里取出数量各不相同的药片,根据质量的总和减去“期望的”质量总和,就知道哪瓶有问题了。

代码:

 1 // 6.1 There are 20 bottles of pills, all of which have pills of 1g, except one with 1.1g.
 2 // Given a balance that can provides exact measurement, can you devise a method to find out the special bottle with just one try?
 3 // Answer:
 4 //    If you pick n[i] pills from bottle i, the total weight should be sigma(n[i] * 1.0).
 5 //    But there is one with 1.1g pills, that would cause a little deviation to the sum.
 6 //    For example, if we pick i pills from bottle i, the sum should be (20 + 1) * 20 / 2 = 210.
 7 //    The real weight w should be greater than 210, (w - 210) / (1.1 - 1.0) will be the number.
 8 int main()
 9 {
10     return 0;
11 }

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3610496.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值