Rust program to count the number of bits to be flipped to convert a number to another number

Given two integer numbers, write a Rust program to count the number of bits to be flipped to convert a given first number to another (second) number.
Submitted by Nidhi, on September 25, 2021

Problem Solution:

Here, we will create two 32-bit integer numbers and then we will read numbers from the user and count the bits to be flipped to convert the first number to the second number.

Program/Source Code:

The source code to count the number of bits to be flipped to convert a number to another number is given below. The given program is compiled and executed successfully.

// Rust program to count number of bits to be flipped
// to convert a number to another number

use std::io;

fn main() {
    let mut num1:i32 = 0;
    let mut num2:i32 = 0;
    let mut lsb1:i32 = 0;
    let mut lsb2:i32 = 0;
    let mut cnt:i32 = 0;
    
    let mut input1 = String::new();
    let mut input2 = String::new();
    
    println!("Enter number1: ");
    io::stdin().read_line(&mut input1).expect("Not a valid string");
    num1 = input1.trim().parse().expect("Not a valid number");

    println!("Enter number2: ");
    io::stdin().read_line(&mut input2).expect("Not a valid string");
    num2 = input2.trim().parse().expect("Not a valid number");

    println!("Num1: {}",num1);
    println!("Num2: {}",num2);
 
    while (num1 > 0) || (num2 > 0) 
    {
        lsb1 = num1 & 1;
        lsb2 = num2 & 1;

        if lsb1 != lsb2
        {
            cnt=cnt+1;
        }

        num1 = num1 >> 1;
        num2 = num2 >> 1;
    }   
    
    println!("Number of bits flipped: {}",cnt);
}

Output:

RUN 1:
Enter number1: 
4
Enter number2: 
7
Num1: 4
Num2: 7
Number of bits flipped: 2

RUN 2:
Enter number1: 
16
Enter number2: 
255
Num1: 16
Num2: 255
Number of bits flipped: 7

RUN 3:
Enter number1: 
16
Enter number2: 
16
Num1: 16
Num2: 16
Number of bits flipped: 0

Explanation:

Here, we created two integer variables num1, num2 with initial value of 0. Then we read the value of variables from the user. After that, we found the total number of bits to be flipped to convert the first number to the second number and printed the result.

Rust Basic Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.