标签:bsp pre else 浮点 ble off 补码 class div
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
(1)最优解
1 public class Solution { 2 public int NumberOf1(int n) { 3 int count=0; 4 while(n!=0){ 5 n = n&(n-1); 6 count++; 7 } 8 return count; 9 } 10 }
(2)
1 public class Solution { 2 public int NumberOf1(int n) { 3 int count=0; 4 int flag=1; 5 while(flag!=0){ 6 if((n&flag)!=0){ 7 count++; 8 } 9 flag = flag<<1; 10 } 11 return count; 12 } 13 }
(3)注意:>>>是右移补0的逻辑右移,>>是右移补符号位的算术右移
1 public class Solution { 2 public int NumberOf1(int n) { 3 int count = 0; 4 while(n!=0){ 5 if((n&1)==1){ 6 count++; 7 } 8 n = n>>>1; 9 } 10 return count; 11 } 12 }
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。(1)
1 public class Solution { 2 public double Power(double base, int exponent) { 3 if(exponent==0) return 1; 4 if(exponent<0){ 5 return 1/base*(Power(base, exponent+1)); 6 }else{ 7 return base*(Power(base, exponent-1)); 8 } 9 } 10 }
标签:bsp pre else 浮点 ble off 补码 class div
原文地址:https://www.cnblogs.com/sjxbg/p/8910002.html