ADVERTISEMENT
ADVERTISEMENT

Rust program to find the next number power of 2

Here, we are going to learn how to find the next number power of 2 in Rust programming language?
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 find the next number, which is the power of 2 using bitwise operators.

Program/Source Code:

The source code to find the next number power of 2 is given below. The given program is compiled and executed successfully.

// Rust program to find the next number power of 2.

use std::io;

fn main() {
    let mut num:i32 = 0;
    let mut val:u32 = 0;
    let mut X:i32 = 2;
    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");

    num=num-1;

    while val <= 4 {
        num = num | (num >> X.pow(val));
        val = val +1;
    }

    num=num+1;

    println!("The next number, power of 2 is: {}", num);
}

Output:

RUN 1:
Enter number: 
14
The next number, power of 2 is: 16

RUN 2:
Enter number: 
5
The next number, power of 2 is: 8

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 and found the next number, which is the power of 2 using bitwise operators, and printed the result.

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.