Skip to content

Instantly share code, notes, and snippets.

@jikeytang
Last active August 29, 2015 14:04
Show Gist options
  • Save jikeytang/4e0120a1b2a65a2e55de to your computer and use it in GitHub Desktop.
Save jikeytang/4e0120a1b2a65a2e55de to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140731-题目1
给出一个数,求最接近此数的2的幂。
比如1最接近的数是1
比如2最接近的数是2
比如5最接近的数是8。
PS:
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。
```javascript
// you code
```
2. 粘贴代码时请使用shift+tab,缩进前面的空白。
@dongzhouT
Copy link

function getNum(number){
  var num=number*2;
  for(i=1;i<num;i=i*2){
    if(number===i){
      return i;
    }else if(number<i &&number>i/2)
      return (i-number)<(number-i/2)?i:i/2;    
  }   
  return 0;
}

@replace5
Copy link

function a(n){
   return  --n ? Math.pow(2, n.toString(2).length) : 1;
}

@ljkfgh2008
Copy link

function a(x){return  x&x-1 ? 1<<x.toString(2).length : x;}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment