First, let's take a look at how to shift the number cyclically.
The C language does not provide the cyclic shift operator, but it can be implemented in a concise way, mainly using the shift operation.
If an operand X has s-bit, the operation that shifts N-bit to the left is:
(X <n) | (x> (S-N ));
Similarly, shift n places to the right:
(X> N) | (x <(S-N ));
In actual programming, the macro definition can be used to implement cyclic shift:
# Define rotate_left (x, S, N) (x) <(N) | (x)> (S)-(n )))
# Define rotate_right (x, S, N) (x)> (N) | (x) <(S)-(n )))
Below is a small test program:
#define ROTATE_LEFT(x, s, n) ((x) << (n)) | ((x) >> ((s) - (n)))#define ROTATE_RIGHT(x, s, n) ((x) >> (n)) | ((x) << ((s) - (n)))int main(){ unsigned int a=0x12345678; unsigned b=ROTATE_LEFT(a, 8 * sizeof(int), 4); unsigned c=ROTATE_RIGHT(a, 8 * sizeof(int), 8); printf("original :%08x\n",a); printf("rot_left :%08x\n",b); printf("rot_right:%08x\n",c); return 0;}
The output result is as follows:
Next, we will discuss how to shift strings.
Question: give you a string that requires the loop to shift n places leftFor example, if the "abcdefg" loop shifts two places to the left, we need to get "cdefgab"
Additional conditions: continuous auxiliary space (including Dynamic Allocation) cannot be used. Only a few single variables (I .e., O (1) space) can be used, we can achieve this by repeating the shift of the number above, as shown below:
Move cycle left |
Shift right of Loop |
Void left_shift (char * STR, int N) {int Len = strlen (STR); char * arr = (char *) malloc (sizeof (char) * Len + 1 ); printf ("% s \ n", STR); strncpy (ARR, STR + N, len-N); // set [N, Len) the characters in the interval are left shifted to N locations printf ("% s \ n", arr); strncpy (ARR + len-N, STR, n); // set [0, n) the characters in the range are shifted right from Len-N locations to cout <"arr =" <arr <Endl; strncpy (STR, arr, Len ); // copy the moved characters back to the original string free (ARR );} |
Void right_shift (char * STR, int N) {int Len = strlen (STR); char * arr = (char *) malloc (sizeof (char) * Len + 1 ); printf ("% s \ n", STR); strncpy (ARR, STR + len-N, N); // set [0, len-N) the range characters are shifted to N places ("% s \ n", arr); strncpy (ARR + N, STR, len-N); // set [N, Len) the characters in the interval are left shifted to Len-N locations printf ("% s \ n", arr); strncpy (STR, arr, Len ); // copy the moved characters back to the original string free (ARR );} |
|
|