Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

พิมพ์ตัวเลขที่มีบิตเซตเพียงบิตแรกและบิตสุดท้ายเท่านั้น

งานคือพิมพ์ตัวเลข n ตัวที่มีบิตเซต (set bits) อยู่ที่บิตแรกและบิตสุดท้ายเท่านั้น (มีบิตเซตอยู่ที่ 2 ตำแหน่งเท่านั้น)

Set bits ในภาษาคอมพิวเตอร์คือบิตที่มีค่า 1 ส่วน unset bits มีค่า 0

Input: num = 5
Output: 1 3 5
    1 = 1 ใน binary
    3 = 11 ใน binary
    5 = 101 ใน binary

อัลกอริทึม

START
Step 1 -> declare variable as unsigned int num=5 and int i=1
Step 2 -> print i
Step 3 -> Loop For i=3 and i<=num and ++i
    IF (!(i-1 & i-2))
        Print i
    End
End
STOP

ตัวอย่างโค้ด (C)

#include <stdio.h>

int main(int argc, char const *argv[]) {
    unsigned int num = 5;
    int i = 1;
    printf("%d ", i); // print 1 first
    for (i = 3; i <= num; ++i) {
        if (!(i-1 & i-2)) // AND operation on i-1 and i-2
            printf("%d ", i);
    }
    return 0;
}

ผลลัพธ์

1 3 5