10月29日网宿的面试题:
问题1,用一行表达式判断任意一个数是否是2的幂(2,4,8,16.........)。
问题2,给一个可能有负数的整形数组,如(1,32,-2,-55,10,0,99,),写一个你认为最高效的程序返回它所有子串的和的最大    值,并求出它的时间复杂度。

解决方案 »

  1.   

    public class Power{
    public static void main(String args[]){
    int[] array = {2, 3, 4, 6, 8};

    for (int i=0; i<array.length; i++){
    int n = array[i];

    System.out.println(Math.log10(n) % Math.log10(2) == 0);
    }
    }
    }数学很重要...
      

  2.   

    不好意思  出错了  shit!!!
      

  3.   

    第一题: 不用移位,对于整数i,如果(i&(i-1))==0成立即可.因为若i为2的幂,则二进制表示第一位是1,其余全是0,而i-1是第一位是0,其余全是1.
    测试:public class Main{
        public static void main(String[] args) {
             for(int i=2;i<100;i++){
                 if((i&(i-1))==0){
                     System.out.println(i);
                 }
             }
        }
    }
      

  4.   

    2.
    public static void func(int[] array) {
    int m = 0;
    int result = 0;
    for (int i = 0; i < array.length; i++) {
    m = m + array[i] > 0 ? m + array[i] : 0;
    result = result > m ? result : m;
    }
    System.out.println(result);
    }
    时间复杂度O(n)
      

  5.   

    (i&(i-1))==0这不就是一行吗,别的是测试用的.
      

  6.   

    不好意思,少了对括号,(n>0)?((n&(n-1))==0):false;
      

  7.   

    嗯,是我看错了。如果这样表示boolean flag = &(n-1)?ture:false;就更好了。
    强大
      

  8.   

    不好意思,写错了boolean flag = n&(n-1)?ture:false;
      

  9.   

    第二题:实在没什么效率,求更高效率解。public int[] Test = new int[] { 8, 13, -1, 10, -2, -30, 10, 0, -2, 30, 20, 10, -5, -1, -1,1 };
    public int Max = 0;public int Compute(int CurVal, int pos)
    {
       if (CurVal > Max) Max = CurVal;
       if (pos > Test.Length - 1) return CurVal;//数组结束
       return Compute(CurVal + Test[pos], pos + 1);
    } Subject3 lobj_Test = new Subject3();
     for (int i = 0; i < lobj_Test.Test.Length - 1; i++)
     {
       lobj_Test.Compute(lobj_Test.Test[i], i+1);
     }
                
     MessageBox.Show(lobj_Test.Max.ToString());