假设你有8个外观相同的球,其中一个比其他稍重。如果给你一个天平,最少称几次你可以找出这只稍重的球?
用java程序写出
谢谢

解决方案 »

  1.   

    3次吧,假设球是以编号区分的
    public int BinaryFind(int from,int to)
    {
       if(from>=to)   return from;
       if(weight(from,to/2)<weight(to/2+1,to)   //二分数据
        {
           from=to/2+1;           //球被分到重的哪一组
           BinaryFind(from,to);
        }
        else
        {
          to=to/2
          BinaryFind(from,to);
         }
    }
      

  2.   

    产生1~8的随机数
    Random random = new Random();
    int count = random.nextInt(9);
    下面是switch结构 这样行不?
      

  3.   

    也不是不行,第一次放三(2组)球,若等重则测剩下的两个球。否则对剩下的重的组(三个球),取两个放上天平即可。
    算法描述如下:(可能有点问题,毕竟没测试,但思路就是这样了,不太好意思。)
    public int CompleteFind(int from,int to)
    {
         if(weight(from,(to-from-2)/2)==weight((to-from-2)/2),to-2))
         {
            if(weight(to-1)<weight(to))
                 return to;
            else
                 return to-1;
         }
         else
         {
              if(weight(from,(to-from-2)/2)<=weight((to-from-2)/2),to-2))
              {
                 from=(to-from-2)/2+1;
                 CompleteFind(from,to);
              }
              else
              {
                to=(to-from-2)/2;
                CompleteFind(from,to);
              }
         
    }