某著名公司的一道JAVA笔试题

来源:互联网 发布:淘宝怎么用手机上架 编辑:程序博客网 时间:2024/05/17 01:53
 如果10 = 1 + 9;
10 = 1 + 2 + 7;
.................
如何1+9 和9 + 1被认为是同一个
那么对于10000 ,可以有多少种加法?


。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

从给出的例子:
10=1+9;
10=1+2+7;
来看,没有10=2+8;,所以也应该没有10=1+3+6;10=1+4+5;等情况。
而1+9与9+1是一种情况,所以各个加数只能是增长关系,即排在前面的加数要大于后面的。
因此给书算法:
如果想看具体的情况的话可以把/*  */注释去掉。

这样做出来的结果是 139


public class ClassTest{
    public static void main(String args[]){
        int count=0;
        System.out.println("/nCOUNT="+printPeases(10000)+"/n");
    }
   
    //compare the whole number as a peasecod
    //and numbers composef of it as pea
    static int printPeases(int peasecod){
        int count=0;
        //each repetition, peasecod=1+2+3+...+i+(left),
        //while lastPease<=left or couninue the repetition
        //until i>=peasecod/2
        for(int lastPease=1;;lastPease++){
            int sum=0,left=0;
            //lastPease is coinsidely the serial number
            /************************************
             System.out.print("NO."+lastPease+":  ");
             ************************************/
            //to calculate sum
            for(int j=1;j<=lastPease;j++){
                sum+=j;
            }
            left=peasecod-sum;
            //ensure the following number is larger than the last one
            //and print out the "pea" composed the peasecod
            if(lastPease<=left){
                /*********************************
                 System.out.print(peasecod+"= ");
                for(int j=1;j<=lastPease;j++){
                    System.out.print(j+" +");
                }
                System.out.print(left);
                System.out.println();
                ***********************************/
            }
            //once the following number is smaller than the last one
            //end the hunting repetition
            else{
                count=lastPease-1;
                System.out.println();
                break;
            }
        }
        return count;
    }
}


后记:
如果不把打印语句注释掉的话,则执行速度要慢好多倍。可见打语句在JAVA中占用很大的执行时间。

做完后跑去考同学,只有JQ在,于是产生了一段对话:

火消しの風 15:23:42
你花了多少时间?
 火消しの風 15:23:49
做这个
Stella 15:32:22
不记得了
很长时间吧
 
Stella15:33:06
就是不知道结果对不对
 
 火消しの風 15:25:31
能想出一种方法来已经很8错了,我很少接触这中类型的题
Stella 15:34:39
我也是看一眼就躲避
不过刚考完试
电影都懒得看了
只好拿来消磨时间
 
 火消しの風 15:27:58
考完试就没事了?做自己感兴趣的事啊,别浪费时间,练这中类型的题对思维逻辑好象挺有帮助的,就是有点枯燥 

Stella 15:36:55
恩?
你在做什么?
 
 火消しの風 15:28:43
我现在还在看JAVA WEB 

火消しの風 15:31:20
偶尔消遣倒时没什么,放松一下嘛,就是别整天都堕落了,我们这边男生很多就是那样的。

虽然在学习方面我和他的观点有分歧,但是,不妨碍我说:
有这样的朋友,幸福!