publicintNumberOf1(int n){//数字在计算机中以二进制形式存储,负数在计算机中以补码存储,int类型的数据占4个字节//为了防止负数右移出现死循环的情况,可以把1每次左移一位,然后和n比较int res =0;int flag =1;while(flag !=0){if((n & flag)!=0){
res++;}
flag = flag <<1;}return res;}publicintNumberOf1Improve(int n){//(n-1)&n 每次运算的结果将n中二进制表示最右边的1变为0int res =0;while(n !=0){
n=(n-1)&n;
res++;}return res;}
16 数值的整数次方
base=0,exponent<0是非法输入,给用户提示输入错误
提高运算效率:
publicclassNumberExponent_16{publicdoublePower(double base,int exponent){//非法输入if(base ==0&& exponent <0){thrownewRuntimeException("input number error!");}double res =1;double tmp = exponent;if(exponent <0){
exponent =-exponent;}//O(n)for(int i =1; i <= exponent; i++){
res = res * base;}if(tmp <0){
res =1/ res;}return res;}publicdoublePowerImprove(double base,int exponent){//非法输入if(base ==0&& exponent <0){thrownewRuntimeException("input number error!");}double res =1;double tmp = exponent;if(exponent <0){
exponent =-exponent;}if(exponent %2==0){//O(n/2)for(int i =1; i <= exponent /2; i++){
res = res * base;}
res = res * res;}else{for(int i =1; i <=(exponent -1)/2; i++){
res = res * base;}
res = res * res * base;}if(tmp <0){
res =1/ res;}return res;}}