整数转换-C语言/Java

描述

整数转换。编写一个函数,确定需要改变几个位才能将整数A转成整数B。A,B范围在[-2147483648, 2147483647]之间。

示例1:

输入:A = 29 (或者0b11101), B = 15(或者0b01111)
输出:2

示例2:

输入:A = 1,B = 2

 输出:2

分析:确定需要改变几个位才能将整数A转成整数B是说A需要改变几个二进制位才能转换为B,也就是A中有几个不同于B的二进制位,需用位运算和移运算

 C语言

int convertInteger(int A, int B){

    int a=A^B;//按位异或

    int count=0;

    while(a){

        if((a & 1) != 0){

            count++;//计算1的个数

        }

        a>>= 1;//从a的最右侧的二进制位开始比较,位数依次向右移一位,最左侧补符号位

    }

    return count;

}

int main(){

    int a,b;

    scanf("%d%d",&a,&b);

    int count=convertInteger(a,b);

    printf("%d",count);

}

Java

import java.util.Scanner;
public class Solution {
    public static int convertInteger(int A, int B) {
        int a=A^B;//按位异或
        int count=0;
        int i;
        for(i=31;i>=0;i--)
        {
            if(((a>>>i)&1)==1)//向右移i位,最左侧补0
                count++;//计算1的个数
        }
        return count;
    }
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int a= sc.nextInt();
        int b= sc.nextInt();
        int count=convertInteger(a,b);
        System.out.println(count);
        sc.close();
    }
}

 

 

  • 12
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值