标签:面试题
check a int number is power of 2?
个人信息:就读于燕大本科软件工程专业 目前大三;
本人博客:google搜索“cqs_2012”即可;
个人爱好:酷爱数据结构和算法,希望将来从事算法工作为人民作出自己的贡献;
博客内容:how many does the factorial of n have zero?
博客时间:2014-5-7;
编程语言:Java ;
编程坏境:Windows 7 专业版 x64;
编程工具:jdk,eclipse x64;
制图工具:office 2010 ppt;
硬件信息:7G-3 笔记本;
my words
problemevery problem has a or more solutions.
my solutioncheck a int number is power of 2?
eg: 1 = 2^0;
2 = 2^1;
4 = 2^2;
5 != 2^2 and 5 != 2^3
make true the function: bool _check_power_2(int n)
program run out follows
0 false 1 true 2 true 3 false 4 true 5 false 6 false 7 false 8 true 9 false 10 false 11 false 12 false 13 false 14 false 15 false 16 true 17 false 18 false 19 false 20 false 21 false 22 false 23 false 24 false 25 false 26 false 27 false 28 false 29 false 30 false 31 false 32 true 33 false 34 false 35 false 36 false 37 false 38 false 39 false 40 false 41 false 42 false 43 false 44 false 45 false 46 false 47 false 48 false 49 false 50 false 51 false 52 false 53 false 54 false 55 false 56 false 57 false 58 false 59 false 60 false 61 false 62 false 63 false 64 true 65 false 66 false 67 false 68 false 69 false 70 false 71 false 72 false 73 false 74 false 75 false 76 false 77 false 78 false 79 false 80 false 81 false 82 false 83 false 84 false 85 false 86 false 87 false 88 false 89 false 90 false 91 false 92 false 93 false 94 false 95 false 96 false 97 false 98 false 99 false
my codeas for a int number n
the binary data of n only have one 1, then it is, or not.
eg:
find regularity, the number of power of 2 only has one 1.
so if( n & (n-1) == 0 ) return true; else return false;
package test; public class test { public static void main(String[] args) { for(int i=0;i<100;i++) { System.out.println(i+" "+_2_pow(i)); } } static boolean _2_pow(int n) { if( n > 0 ) { int i = (n-1) & n ; if(i == 0) return true; else return false; } else return false ; } }
check a int number is power of 2?,布布扣,bubuko.com
check a int number is power of 2?
标签:面试题
原文地址:http://blog.csdn.net/cqs_experiment/article/details/25201607