비트 연산으로 10진법을 2진법으로 변환하다
7693 단어 진수 변환
1 #include <iostream> // ,
2 using namespace std;
3 int main()
4 {
5 unsigned short i;
6 cout << " 65536 " << endl;
7 cin >> i;
8 for(int j=15; j >= 0; j--)
9 {
10 if ( i & ( 1 << j) ) cout << "1";
11 else cout << "0";
12 }
13 cout << endl;
14
15 return 0;
16 }
분석:
이 프로그램의 알고리즘 원리를 분석하는 김에 비트 연산의 기묘함을 복습해 봅시다.
이것은 무기호 십진수를 표준 16자리 이진수로 바꾸는 프로그램이다.
프로그램의 주체 부분인 for문장은 15에서 0으로 체감하여 모두 16차례에 걸쳐 이진수 한 분의 판단을 조작한다.순환체 내부의 조건 판단은 비트 연산에서의 & 연산(과 연산)과 <<<연산(좌이동 연산)을 사용합니다.<<연산은 1의 2진법 형식을 전체적으로 왼쪽으로 j위를 옮기고 왼쪽으로 옮긴 후 낮은 위치에서 0을 보충하며 옮긴 높은 부분은 버려진다는 것을 나타낸다.예를 들어 j가 15일 때 표현식(1<
비슷한 LeetCode의 첫 번째 문제:
Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight ).
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011
, so the function should return 3. Credits:Special thanks to @ts for adding this problem and creating all test cases.
정수 n의 Hamming weight, 즉 2진수 중 0이 아닌 개수를 계산한다.
AC 코드:
1 int hammingWeight(uint32_t n) {
2 int i, ans=0;
3 for (i=31; i>=0; i--)
4 {
5 if (n & (1 << i)) ans++;
6 }
7 return ans;
8 }
LetCode의 두 번째 문제:
Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up: If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
Credits:Special thanks to @ts for adding this problem and creating all test cases.
AC 코드:
1 uint32_t reverseBits(uint32_t n) {
2 int i;
3 uint32_t ans;
4
5 if (n & 1) ans=1;
6 else ans=0;
7 for (i=1; i<=31; i++)
8 {
9 ans <<= 1;
10 if ((n & (1 << i))) ans |= 1;
11 }
12
13 return ans;
14 }
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
비트 연산으로 10진법을 2진법으로 변환하다이 프로그램의 알고리즘 원리를 분석하는 김에 의 기묘함을 복습해 봅시다. 프로그램의 주체 부분인 for문장은 15에서 0으로 체감하여 모두 16차례에 걸쳐 이진수 한 분의 판단을 조작한다.순환체 내부의 조건 판단은 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.