ADVERTISEMENT
ADVERTISEMENT

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 »



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.