Q:

Rust program to check a number contain the alternative pattern of bits

belongs to collection: Rust Basic Programs

0

Here, we will create a 16-bit integer number and then we will check the number contains the alternate pattern of bits or not.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to check a number contain the alternative pattern of bits is given below. The given program is compiled and executed successfully.

// Rust program to check a number contain 
// the alternative pattern of bits

fn main() {
    let mut num:i16 = 10;
    let mut val:i16 = 0;
    let mut cnt:i16 = 0;
    let mut flg:i16 = 0;
    
    let mut tmp:i16 = 0;
    let mut tmp1:i16 = 0;
    let mut tmp2:i16 = 0;
    
    println!("Decimal Number: {}",num);
    println!("Binary Number: {:#02b}",num);
    
    tmp = num;
    while tmp>0 {
        cnt=cnt+1;
        tmp = tmp >> 1;
    }
    
    while val< cnt-1
    {
        tmp1 = (num >> val) & 1;
        tmp2 = (num >> (val + 2)) & 1;
        
        if tmp1== tmp2
        {
            val = val + 1;
        }
        else 
        {
            flg=1;
            break;
        }
    }
 
    if flg==1
    {
        println!("Alternate BIT pattern does not exist");
    }
    else
    {
        println!("Alternate BIT pattern exists");
    }
}

Output:

Decimal Number: 10
Binary Number: 0b1010
Alternate BIT pattern exists

Explanation:

Here, we created an integer variable num with an initial value of 10. Then we checked the given number contains the alternat pattern of bits and printed the appropriate message.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Rust program to find the next number power of 2... >>
<< Rust program to check a given number EVEN or ODD u...