java中的位操作问题
2015-06-03 15:02
387 查看
在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值
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值
相关文章推荐
- struts2的零配置
- Spring MVC controller中返回json中午数据乱码,及HashMap转化json数据
- Java的日期格式化常用方法
- 使用Spring和Hibernate做一个留言板。
- spring+mybatis+atomikos 实现JTA事务
- Java中的instanceof关键字
- spring事件派发
- java I/O 操作及优化建议
- Eclipse程序打包
- 学习 Activiti5.13与springMVC整合,自学001期
- JAVA编程思想学习总结:第十四章类型信息
- Java中的集合--初级
- Java中对象创建与引用
- java程序作业代码
- 我们打赌:这个注解很快就会出现在JDK里面
- velocity 显示List和Map方法
- 致我曾经敲过的代码——初涉JAVA 自定义链表的实现
- Eclipse中配置JAD、JADCLIPSE反编译器
- Eclipse常用的快捷方式
- Spring-程序中获取注册bean的方式