>  기사  >  백엔드 개발  >  C 프로그램에서 2^X - 1 형식의 숫자를 생성하는 단계를 인쇄하세요.

C 프로그램에서 2^X - 1 형식의 숫자를 생성하는 단계를 인쇄하세요.

WBOY
WBOY앞으로
2023-09-07 14:01:02472검색

打印在C程序中生成形如2^X - 1的数字的步骤

숫자 n이 주어지면 XOR 연산을 사용하여 숫자를 2^X-1 형식으로 만드는 단계를 인쇄해야 합니다.

  • 귀하가 M을 선택한 2^M-1 숫자를 이상한 단계로 XOR해야 합니다.
  • 짝수 단계에서는 숫자를 1 증가시킵니다.

n이 2^X-1이 될 때까지 단계를 계속하고 모든 단계를 인쇄합니다.

Example

Input: 22
Output:
   Step 1 : Xor with 15
   Step 2: Increase by 1
   Step 3 : Xor with 7
   Step 4: Increase by 1
   Step 5 : Xor with 1
Input:7
Output: No Steps to be performed

Algorithm

int find_leftmost_unsetbit(int n)
START
STEP 1 : DECLARE AND ASSIGN ind = -1, i = 1
STEP 2 : LOOP WHILE n
   IF !(n & 1) THEN,
      ASSIGN ind WITH i
   END IF
   INCREMENT i BY 1
   LEFT SHIFT n BY 1
END WHILe
STEP 3 : RETURN ind
STOP
void perform_steps(int n)
START
STEP 1 : DECLARE AND ASSIGN left = find_leftmost_unsetbit(n)
STEP 2 : IF left == -1 THEN,
   PRINT "No Steps to be performed"
   RETURN
END IF
STEP 3 : DECLARE AND ASSIGN step = 1
STEP 4 : LOOP WHILE find_leftmost_unsetbit(n) != -1
   IF step % 2 == 0 THEN,
      INCREMENT n BY 1
      PRINT "Step n : Increase by 1</p><p>"
   ELSE
      DECLARE AND ASSIGN m =
      find_leftmost_unsetbit(n)
      AND SET num = (pow(2, m) - 1)
      SET n = n ^ num
      PRINT "Step N : Xor with Num
   END IF
   INCREMENT step BY 1
END LOOP
STOP

Example

#include <stdio.h>
#include <math.h>
//To find the leftmost bit
int find_leftmost_unsetbit(int n){
   int ind = -1;
   int i = 1;
   while (n) {
      if (!(n & 1))
         ind = i;
      i++;
      n >>= 1;
   }
   return ind;
}
void perform_steps(int n){
   // Find the leftmost unset bit
   int left = find_leftmost_unsetbit(n);
   //If there is no bit
   if (left == -1) {
      printf("No Steps to be performed</p><p>");
      return;
   }
   // To count the number of steps
   int step = 1;
   // Iterate till number is in form of 2^x - 1
   while (find_leftmost_unsetbit(n) != -1) {
      // if the step is even then increase by 1
      if (step % 2 == 0) {
         n += 1;
         printf("Step %d: Increase by 1</p><p>", step);
      }
      // if the step is odd then xor with 2^m-1
      else {
         // Finding the leftmost unset bit
         int m = find_leftmost_unsetbit(n);
         int num = (int)(pow(2, m) - 1);
         n = n ^ num;
         printf("Step %d : Xor with %d</p><p>", step, num);
      }
      // To increase the steps
      step += 1;
   }
}
int main(){
   int n = 22;
   perform_steps(n);
   return 0;
}

Output

위 프로그램을 실행하면 다음과 같은 출력이 생성됩니다 -

Step 1 : Xor with 15
Step 2 : Increase by 1
Step 3 : Xor with 7
Step 4 : Increase by 1
Step 5 : Xor with 1

위 내용은 C 프로그램에서 2^X - 1 형식의 숫자를 생성하는 단계를 인쇄하세요.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제