#include <iostream>
usingnamespace std;
int main()
{
int nr,n = 0,num = 0,k,v[100],i = 0;
cout <<"n = ";
cin >> nr;
cout <<"k = ";
cin >> k;
while (nr){
v[i] = nr%10;
num++;
nr/=10;
i++;
}
for (i = k-1;i >= 0;i--){
n = n*10+v[i];
}
for (i = num-1;i >= k;i--) {
n = n*10+v[i];
}
cout << n;
return 0;
}
I don't know if this is right.Could you please tell me whether my program is correct or not ? And if not,please tell me what's wrong so I can fix the problem.
Thanks in advance !
Not sure if it's right or not. I inputted 123456, with k being 1, and I ended with a result of 612345. The 6 being rotated to the LEFT. Should it have been 234561, as the result? Then, the number would have been shifted RIGHT.
based on your description, I would assume the output whitenite got was correct. That example sucks btw plus - it's the same rotated left or right.
For completeness: 'int' data types are of limited size, so you will only be able to hold 2^31 for a signed integer, which is just over 2 billion (in a 32 bit environment) . Want to really impress the teacher, instead load the number into an std::string container, do your manipulation there, and output the result. This way the teacher can enter a number of /any/ size. Currently you are limited by both the size of 'nr' and the size of your vector '100'.
Unless, of course, the assignment requires you to use 'int'...
Well, PlusPower, with that example, yes, you could say the numbers were rotated to the right, but it's also the same results rotated left. Was more than one example shown? If not, your version does what you set out for it to do.
All he did was create a while loop for the number of digits to shift, which would take the last digit of the number (line 14: num % 10) and output it to a string, as well as removing it from the number (line 16: num /= 10). Once the loop finished he simply outputted the rest of the numbers to the string.
int _tmain(int argc, _TCHAR* argv[])
{
int num = 0 , rotate = 0 , num_array[100];
string numstr ;
char buffer[50];
ostringstream str (stringstream::in | stringstream::out);
cout <<"number = ";
cin >> num;
cout <<"\n rotate by = ";
cin >> rotate ;
while (rotate)
{
// itoa(num%10, buffer , 10); // convert last digit to string
numstr += '0' + (num % 10); // more efficient than above
num /=10; // last digit is lost using this division
rotate--;
}
itoa(num, buffer, 10); // convert whatever is left in num into a char buffer
numstr += buffer; // append the buffer to output string
num = atoi( numstr.c_str() ); // convert string back to integer? could just print this instead whatever you need it to do...
numstr.erase();
cout << num; // print integer
return 0;
}