Easy

Reverse the order of the bits in a given integer.

Example

  • For a = 97, the output should be
    mirrorBits(a) = 67.

    97 equals to 1100001 in binary, which is 1000011 after mirroring, and that is 67 in base 10.

  • For a = 8, the output should be
    mirrorBits(a) = 1.

Input/Output

  • [execution time limit] 0.5 seconds (c)

  • [input] integer a

    Guaranteed constraints:
    5 ≤ a ≤ 10^5.

  • [output] integer

[C] Syntax Tips

// Prints help message to the console
// Returns a string
char * helloWorld(char * name) {
    char * answer = malloc(strlen(name) + 8);
    printf("This prints to the console when you Run Tests");
    strcpy(answer, "Hello, ");
    strcat(answer, name);
    return answer;
}

더보기

Solution

int mirrorBits(int a)
{
	int N=0, *array=NULL, count=0;

	while(a>=(1<<++N));
	array=(int *)calloc(N,sizeof(int));

	for(int i=0;i<N;i++)
		array[N-i-1]=((a&(1<<i))!=0);
	a=0;

	for(int i=0;i<N;i++)
		a+=(int)pow(2,i)*array[i];

	free(array);
	return a;
}
728x90

'Codesignal' 카테고리의 다른 글

<Codesignal> Least Factorial  (0) 2020.04.12
<Codesignal> Second-Rightmost Zero Bit  (0) 2020.04.12
<Codesignal> Range Bit Count  (0) 2020.04.07
<Codesignal> Array Packing  (0) 2020.04.07
<Codesignal> Kill K-th Bit  (0) 2020.04.07

+ Recent posts