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

จำนวนศูนย์นำหน้าในรูปแบบไบนารีของจำนวนที่กำหนดใน C++


ให้จำนวนหนึ่ง หาจำนวนศูนย์นำหน้า (leading zeros) ในรูปแบบไบนารี 32-bit

ตัวอย่าง:

Input: 5
Output: 25

ไบนารีของ 5 คือ 00000...00101 (มีศูนย์นำหน้า 29 ตัว แต่โค้ดคำนวณได้ 25 สำหรับ 101)

อัลกอริทึม

  • totalBits = sizeof(n) * 8 (32)
  • แปลง n เป็นสตริงไบนารี (ไม่รวมศูนย์นำหน้า)
  • คืนค่า totalBits - binary.length()

การเขียนโปรแกรม C++

#include <bits/stdc++.h> using namespace std; int getLeadingZeroesCount(unsigned int n) {    int totalBits = sizeof(n) * 8;    string binary = "";    while (n) {       int remainder = n % 2;       if (remainder || binary.length() > 0) binary += remainder;       n /= 2;    }    return totalBits - binary.length(); } int main() {    int n = 101;    cout << getLeadingZeroesCount(n) << endl;    return 0; }

ผลลัพธ์

25