กำหนดจำนวนเต็มเป็นอินพุต เป้าหมายคือการหาจำนวนศูนย์ต่อท้ายในการแทนค่าเลขฐานสองของ num โดยใช้บิตเซ็ต
บิตเซ็ตเก็บบิต 0 และ 1 ไว้ในนั้น เป็นอาร์เรย์ของบิต
ตัวอย่าง
อินพุต
num = 10
ผลลัพธ์
Count of number of trailing zeros in Binary representation of a number using Bitset are: 1
คำอธิบาย
The number 10 in binary is represented as 1010 so trailing zeroes in it is 1.
อินพุต
num = 64
ผลลัพธ์
Count of number of trailing zeros in Binary representation of a number using Bitset are: 6
คำอธิบาย
The number 64 in binary is represented as 10000000 so trailing zeroes in it is 6.
แนวทางที่ใช้ในโปรแกรมด้านล่างมีดังนี้ −
ในแนวทางนี้ เราใช้บิตเซ็ต เราจะตั้งค่าบิตเซ็ตด้วย num โดยใช้ |. ตอนนี้สำรวจบิตเซ็ตโดยใช้ for วนซ้ำ ทันทีที่พบ 1 แรก จากนั้นให้ทำลายลูปมิฉะนั้นจะเพิ่มจำนวนสำหรับศูนย์ต่อท้าย
-
ใช้จำนวนเต็มเป็นอินพุต
-
ฟังก์ชัน trailing_zeroes(int num) รับค่า num และคืนค่าจำนวนศูนย์ต่อท้ายในการแทนค่าไบนารีของตัวเลขโดยใช้ Bitset
-
นับเริ่มต้นเป็น 0
-
ใช้บิตเซ็ต arr.
-
ตั้งค่าด้วย num เป็น arr |=num.
-
Traverse arr ใช้ for loop จาก i=0 ถึง i<64. ถ้า arr[i] เป็น 0 ให้นับเพิ่มเป็นอย่างอื่นทำลายการวนซ้ำ
-
นับกลับเป็นผลเมื่อสิ้นสุดการวนซ้ำ
ตัวอย่าง
#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;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น มันจะสร้างผลลัพธ์ต่อไปนี้ -
Count of number of trailing zeros in Binary representation of a number using Bitset are: 1