ADVERTISEMENT
ADVERTISEMENT

Rust program to find the total number of leading zeros in a binary number

Given an integer number, write a Rust program to find the total number of leading zeros in its binary.
Submitted by Nidhi, on September 25, 2021

Problem Solution:

Here, we will create a 32-bit integer number and then we will read the number from the user and then print its binary number and count the total number of leading zero.

Program/Source Code:

The source code to find the total number of leading zeros in a binary number is given below. The given program is compiled and executed successfully.

// Rust program to find the total number of 
// leading zeros in a binary number

use std::io;

fn main() {
    let mut num:i32 = 0;
    let mut cnt:i32 = 31;
    let mut tmp:i32 = 0;
    
    let mut input = String::new();
    
    println!("Enter number: ");
    io::stdin().read_line(&mut input).expect("Not a valid string");
    num = input.trim().parse().expect("Not a valid number");
    
    println!("Binary number: ");
    while cnt >= 0 
    {
        tmp = num & (1 << cnt);
        if tmp>0
        {
            print!("1");
        }
        else
        {
            print!("0");
        }
        cnt=cnt-1;
    }

    cnt = 0;
    tmp = num & (1 << 31);
    while tmp==0 
    {
        num = (num << 1);
        cnt=cnt+1;
        tmp = num & (1 << 31);
    }

    println!("\nNumber of leading zero's are: {}", cnt);
}

Output:

RUN 1:
Enter number: 
17
Binary number: 
00000000000000000000000000010001
Number of leading zero's are: 27

RUN 2:
Enter number: 
65535
Binary number: 
00000000000000001111111111111111
Number of leading zero's are: 16

Explanation:

Here, we created an integer variable num with an initial value of 0. Then we read the value of the variable from the user. Then we printed the corresponding binary number and counted the total number of leading zeros in the binary number. After that, we printed the result on the console screen.

Rust Basic Programs »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.