Rust program to round off an integer number to the next lower power 2

Given an integer number, write a Rust program to round off an integer number to the next lower power 2.
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 round off the given number to the next lower power of 2.

Program/Source Code:

The source code to round off an integer number to the next lower power 2 is given below. The given program is compiled and executed successfully.

// Rust program to round off an integer number 
// to the next lower power 2

use std::io;

fn main() {
    let mut num:i32 = 0;
    let mut tmp:i32 = 1;
    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 > 0 
    {
        while tmp <= (num>>1)
        {
            tmp = tmp << 1;
        }
        num = tmp;
    }
    else 
    {
        num = !num;
        num = num + 1;

        while tmp <= (num>>1)
        {
            tmp = tmp << 1;
        }
        
        tmp = tmp << 1;
        tmp = !tmp;
        tmp = tmp + 1;
        num = tmp;
    }
    println!("Result is: {}", num);
}

Output:

RUN 1:
Enter number: 
23
Result is: 16

RUN 2:
Enter number: 
131
Result is: 128

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 round off the given number to the next lower power of 2 and printed the result.

Rust Basic Programs »



Related Programs




Comments and Discussions!

Load comments ↻






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