Rust program to check a given number is the power of 2 using bitwise operator

Given an integer number, write a Rust program to check whether it is the power of 2 or not using bitwise operator.
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 check the given number is the power of 2 using bitwise operators.

Program/Source Code:

The source code to swap two bits of a 32-bit integer number is given below. The given program is compiled and executed successfully.

// Rust program to check a given number 
// is power of 2 using bitwise operator

use std::io;

fn main() {
    let mut num: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");

    if (num & (num - 1)) != 0
    {
        println!("Given number is not power of 2.");
    }
    else
    {
        println!("Given number is power of 2.");
    }
}

Output:

RUN 1:
Enter number: 
16
Given number is power of 2.

RUN 2:
Enter number: 
128
Given number is power of 2.

RUN 3:
Enter number: 
250
Given number is not power of 2.

Explanation:

Here, we created an integer variable num with the initial value of 0. Then we read the value of num from the user. After that, we checked the given number is a power of 2 or not and printed the appropriate message.

Rust Basic Programs »



Related Programs




Comments and Discussions!

Load comments ↻






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