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

นับศูนย์นำหน้ารูปแบบไบนารีของตัวเลขด้วย Bitset ใน C++

ได้รับจำนวนเต็ม num เป็นอินพุต เป้าหมายคือหาจำนวนศูนย์นำหน้า (trailing zeros) ในรูปแบบไบนารีของ num โดยใช้ bitset

Bitset เก็บบิต 0 และ 1 เป็นอาร์เรย์ของบิต

ตัวอย่าง

Input

num = 10

Output

Count of number of trailing zeros in Binary representation of a number using Bitset are: 1

Explanation

The number 10 in binary is represented as 1010 so trailing zeroes in it is 1.

Input

num = 64

Output

Count of number of trailing zeros in Binary representation of a number using Bitset are: 6

Explanation

The number 64 in binary is represented as 10000000 so trailing zeroes in it is 6.

วิธีการที่ใช้ในโปรแกรม

วิธีนี้ใช้ bitset จะตั้งค่า bitset ด้วย num โดยใช้ | จากนั้นวนลูปผ่าน bitset ทันทีที่เจอ 1 แรกให้ break ลูป มิฉะนั้นเพิ่ม count สำหรับศูนย์นำหน้า

  • รับจำนวนเต็ม num เป็นอินพุต
  • ฟังก์ชัน trailing_zeroes(int num) คืนค่าจำนวนศูนย์นำหน้าในรูปแบบไบนารี
  • กำหนดจำนวนนับเริ่มต้นเป็น 0
  • สร้าง bitset<64> arr
  • ตั้งค่าด้วย num: arr |= num
  • วนลูป arr จาก i=0 ถึง i<64 ถ้า arr[i] == 0 เพิ่ม count มิฉะนั้น break
  • คืนค่า count เป็นผลลัพธ์

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

#include <bits/stdc++.h>
using namespace std;

int trailing_zeroes(int num){
    int count = 0;
    bitset<64> arr;
    arr |= num;
    for (int i = 0; i < 64; i++){
        if (arr[i] == 0){
            count++;
        } else {
            break;
        }
    }
    return count;
}

int main(){
    int num = 6;
    cout << "Count of number of trailing zeros in Binary representation of a number using Bitset are: " << trailing_zeroes(num);
    return 0;
}

Output

หากรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้:

Count of number of trailing zeros in Binary representation of a number using Bitset are: 1