只允许用一行代码实现(不能出现while或for循环)

解决方案 »

  1.   

    if(n & (n-1) == 0) return true;
    else return false;
      

  2.   

    Integer.toBinaryString(i).indexOf("1") == Integer
    .toBinaryString(i).lastIndexOf("1")
      

  3.   

    return (n & (n-1) == 0)
      

  4.   

    呀 一行代码
    那就是  return (n & (n-1) == 0);
      

  5.   

    Integer.toBinaryString(i).indexOf("1") == Integer
    .toBinaryString(i).lastIndexOf("1")

    n & (n-1)
    其实思路都一样 只是实现方法不一样。
      

  6.   

     return Integer.toBinaryString(i).replaceAll("0", "").length() == 1;?
      

  7.   

    return (num | (num - 1)) == (2*num - 1);
      

  8.   

    我一楼写的好像是错的 应该是 (num & (num-1)) == 0;
    那个少了括号貌似会报错 int & Boolean 非法吧,没IDE 谁试下去;THX
      

  9.   

    你用6试验一下就知道不对:
    110 | 101 = 111 
    110<<2 - 1 = 1011
      

  10.   

    关于6是我说错了,但是你这个算法有个缺陷,那就是当num很大的时候2*num会越界。不能保证对所有的int都适用,对吧?
      

  11.   

    System.out.println(x%(x/2)==0);
    是这个么?
      

  12.   

    有兴趣可以去看看这个帖子:http://topic.csdn.net/u/20100325/17/eda330e1-1aa1-47b8-8691-15a504fa3c0d.html
      

  13.   

    return (n & n-1) == 0 ? true : false;
      

  14.   

    jdk 中 Random.nextInt()方法中提供的一种方法:
    return (n & -n) == n ? true : false;
      

  15.   


    正解,这个方法确实是j2se的API中提到的