代码改变世界

一道微软面试题的Java解法

2010-03-12 12:01  jinze  阅读(335)  评论(0编辑  收藏  举报

问题:你有4瓶药。每粒药丸的重量是固定的,不过其中有一瓶药受到了污染,药丸的重量发生了变化,每个药丸增加了一点重量。你怎样一下子测出哪瓶药是遭到污染的呢?

Java代码:

 

代码
package cn.nx.majinze; 

public class GetMedicine 

    
public static void main(String[] args) 
    { 
        
int[] T={12,17,12,12}; 
        getTrue(T); 
    } 
    
public static void getTrue(int[] T) 
    { 
        
int flag=0
        
for(int i=0;i<T.length;i++
        { 
            
if(flag==0
            { 
                
for(int j=0;j<T.length;j++
                { 
                    
if(flag==0
                    { 
                        
for(int k=0;k<T.length;k++
                        { 
                            
if(flag==0
                            { 
                                
if(i!=j&&j!=k&&i!=k) 
                                { 
                                    
if(T[i]==T[j]&&T[j]==T[k]) 
                                    { 
                                        System.out.println(
"合格的产品已经找到: "+i+j+k); 
                                        flag
=1
                                        
break
                                    } 
                                    
else 
                                    { 
                                        System.out.println(
"算法仍在继续...."); 
                                    } 
                                } 
                            } 
                            
else 
                            { 
                                
break
                            } 
                        } 
                    } 
                    
else 
                    { 
                        
break
                    } 
                } 
            } 
            
else 
            { 
                
break
            } 
        } 
    } 

}

 

 

用电子邮件联系Andy