Left shift integers in array?

Dec 3, 2013 at 7:20pm
How do I leftshift an integer x amount to the left ??
I am bit confused on how i should do it??
It seems like an easy problem, but can't come up with an solution...
Last edited on Dec 3, 2013 at 7:31pm
Dec 3, 2013 at 7:53pm
Hi JohnJH, I'm not sure I understand the question. Could you give us an example of what you want to achieve ?
Dec 3, 2013 at 8:06pm
The input and output (>> and <<) operators are overloaded for this. See examples below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

using namespace std;

int main()
{
	int x = 24;
	cout << x << endl;
	
	// shift left by 2 examples
	int y = x << 2;
	cout << y << endl;
	
	x <<= 2;
	cout << x << endl;
	
	// shift right by 2 examples
	int z = x >> 2;
	cout << z << endl;
	
	x >>= 2;
	cout << x << endl;
	
	return 0;
}
Dec 3, 2013 at 8:12pm
If i had an array [1 2 3 4 6]
I would like to be able to e.g. left shift the number 3 two elements to the left. so the array would end up like this.

[3 1 2 4 6]
Last edited on Dec 3, 2013 at 8:30pm
Dec 3, 2013 at 8:48pm
Ok, I see what you mean now. It is not complicated, but the result will probably not be efficient, and quite long to write. If you can, I would suggest to have a look at the Standard Template Library. You could use list or vector to do that, instead of array.
But if you want to do it with array, here are the first steps that came to my mind:

Build an array of size N-1 from equal to the initial but without the number to be shifted.

Then rebuilding the size N array with a loop on the N-1 array, and an if condition inside the loop to insert the extracted value at the proper place.

Does that make any sens ?
Dec 3, 2013 at 8:55pm
Not exactly...
Dec 4, 2013 at 12:21am
Not at all the question you asked... also, this is a rotation not a shift.

Do you mean something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
static void left_shift(int arr[], size_t arrSize, unsigned shiftBy)
{
	while (shiftBy--)
	{
		int x = arr[0];
		for ( size_t i = 1; i < arrSize; ++i)
		{
			arr[i - 1] = arr[i];
		}
		
		arr[arrSize - 1] = x;
	}
}


You can test it like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

using namespace std;

static void left_shift(int arr[], size_t arrSize, unsigned shiftBy);

int main()
{
	int arr[] = {1, 2, 3, 4, 6};
	const size_t arrSize = sizeof(arr) / sizeof(arr[0]);
	unsigned shiftBy = 2;
	cout << "Before shifting by " << shiftBy << endl; 
	for (size_t i = 0; i < arrSize; ++i)
		cout << arr[i] << " ";
	cout << endl;
	
	left_shift(arr, arrSize, shiftBy);
	
	cout << "After shifting by " << shiftBy << endl;
	for (size_t i = 0; i < arrSize; ++i)
		cout << arr[i] << " ";
	cout << endl;
		
	return 0;
}
Dec 4, 2013 at 11:03pm
I found a way get around it..
Thanks anyway :)
Topic archived. No new replies allowed.