在java中进行位操作的时候,不能像C++那样随意,经常会碰到一些莫名其妙的错误。
public class Main {
private static int c = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
converse(n);
}
public static void converse(int n) {
for(int i=0;i<32;i++){
if( n & 1){
c++;
}
n = n>>1;
}
System.out.println(c);
}
public class Main {
private static int c = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
converse(n);
}
public static void converse(int n) {
for(int i=0;i<32;i++){
Integer flag = n&1;
if(flag){
c++;
}
n = n>>1;
}
System.out.println(c);
}
以上俩种写法,编译器都会报错,在JAVA中的位操作可以说是有比较严格的格式了。
当把代码下面这种方式时,就能获得正确的结果。
public class Main {
private static int c = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
converse(n);
}
public static void converse(int n) {
for(int i=0;i<32;i++){
Integer flag = n&1;
if(flag != 0){
c++;
}
n = n>>1;
}
System.out.println(c);
}
其中的缘由,java中的if表达式只能为BOOLEAN值