Converts an integer to a string, for example,-123 to-123"
This is a written examination question for the IBM campus recruitment in 2013 and is a very basic question. However, there are several very easy mistakes. During my written test, I wrote this basic question wrong, so I did not enter the IBM interview. It can be seen that ordinary exercises are very important.AlgorithmIt must be tested in practice.
1. Check whether the pointer parameters of the input function are correct.
2.Negative number processingIt is easy to ignore because-1% 10 =-1, so remember the negative number first, and then convert the negative number into a positive integer for processing. (I did not take this into consideration during the written examination ......)
3. When the last array is reversed, the loop condition is P <= Q, not p! = Q, otherwise it will easily lead to an endless loop.
Of course, you can also use some APIs to implement conversion operations, such as sprintf and ITOA, which are not described here.
The following is a conventional conversion algorithm, which is expected to be proposed with efficient algorithms. If any error occurs, please correct it. Thank you very much!
-
- # Include <Iostream>
-
- # Include <Stdlib. h>
-
- Using NamespaceSTD;
- //Convert intConvert to char *
-
- /*
-
- Parameters:
-
- Const int Ivar: Integer to be converted
-
- Char * PDEs: Space for storing Integers
-
- */
-
- VoidInttostring (Const
IntIvar,Char* PDES)
-
- {
-
- If(Null = PDES)
-
- {
- Return;
-
- }
-
- IntN = Ivar, flag = 1;
-
- /*
-
- Negative numbers must be specially processed for correct modulo operations !!!
-
- No wonder IBMI am not allowed to enter the interview process.......
-
- */
-
- If(N <0)
-
- {
-
- // NIs negative
- Flag = 0;
-
- N = N * (-1 );
-
- }
-
- IntLast = 0;
-
- Char* P = PDES;
-
- // 1And put it in memory in reverse order.
-
- While(N)
-
- {
-
- Last = n % 10;
-
- * P = last +'0';
-
- P ++;
-
- N/= 10;
-
- }
- // 2Determine whether to add a negative number and add the end sign of the string'\ 0'
-
- If(0 = Flag)
-
- {
-
- * P ='-';
-
- P ++;
-
- }
-
- * P ='\ 0';
-
- // 3, String reverse operation
-
- Char* Q = PDES;
- P --;//Point to the last character, not '\ 0'
-
- CharTemp;
-
- /*
-
- While (P! = Q)
-
- This write will lead to an endless loop, so you cannot take it for granted
-
- */
-
- While(P> = q)
-
- {
-
- Temp = * P;
-
- * P = * q;
-
- * Q = temp;
- P --;
-
- Q ++;
-
- }
-
- }
-
- IntMain ()
-
- {
-
- CharA [50];
-
- Memset (A, 0, 50 );
-
- Inttostring (-8374563, );
-
- Cout <A <Endl;
-
- System ("Pause");
-
- Return0;
-
- }