Medium
You are given an array of up to four non-negative integers, each less than 256.
Your task is to pack these integers into one number M in the following way:
- The first element of the array occupies the first 8 bits of M;
- The second element occupies next 8 bits, and so on.
Return the obtained integer M.
Note: the phrase "first bits of M" refers to the least significant bits of M - the right-most bits of an integer. For further clarification see the following example.
Example
For a = [24, 85, 0], the output should be
arrayPacking(a) = 21784.
An array [24, 85, 0] looks like [00011000, 01010101, 00000000] in binary.
After packing these into one number we get 00000000 01010101 00011000 (spaces are placed for convenience), which equals to 21784.
Input/Output
-
[execution time limit] 0.5 seconds (c)
-
[input] array.integer a
Guaranteed constraints:
1 ≤ a.length ≤ 4,
0 ≤ a[i] < 256. -
[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
// Arrays are already defined with this interface:
// typedef struct arr_##name {
// int size;
// type *arr;
// } arr_##name;
//
// arr_##name alloc_arr_##name(int len) {
// arr_##name a = {len, len > 0 ? malloc(sizeof(type) * len) : NULL};
// return a;
// }
//
//
int arrayPacking(arr_integer a)
{
int M=0;
for(int i=0;i<a.size;i++)
M+=a.arr[i]<<i*8;
return M;
}
'Codesignal' 카테고리의 다른 글
<Codesignal> Mirror Bits (0) | 2020.04.09 |
---|---|
<Codesignal> Range Bit Count (0) | 2020.04.07 |
<Codesignal> Kill K-th Bit (0) | 2020.04.07 |
<Codesignal> Metro Card (0) | 2020.04.07 |
<Codesignal> Will You? (0) | 2020.04.07 |