C/C ++ algorithm series for interview-view the association of algorithms from "Integer Conversion to string"

Source: Internet
Author: User

Http://blog.csdn.net/sailor_8318/article/details/1777759
--------------------------------------------------

[Sequence] converting a given integer to a string is a common question in the interview. This article references the posts of two csdn bloggers. Thank you!

  It is the easiest way to convert from the low position, and then flip the string. First, determine the number of digits of the integer. The modulo operation starts from the low position, and the saved position is decreased, this method does not need to flip the string, so the overall efficiency is high, it is worth learning.   Inspired by the idea of first determining the number of digits of the integer, I think the operator operation can also start from the high level, and it is sequential storage, without the need to flip the string   From the method of obtaining the highest bit, I got another idea, that is, to obtain the highest bit in recursion. The recursion condition is very simple, as long as the parameter is not less than 10, that is, the maximum bit is not found. Of course, the condition for Recursive exit is that the current number is a single digit.   Found manyAlgorithmThere are some commonalities and we can always find some of these connections. I believe that as long as you are good at thinking, you will certainly benefit a lot from different perspectives, including time efficiency and space efficiency. The last recursive algorithm is slightly flawed. Welcome to discuss it!   **************************************** ******** Converts a given integer to a string. Sailor_forever Sailing_9806@163.com Reprinted please note ××××××××××××××××××××××××××××××××× Algorithm-1 counting Interchange   The following algorithm shows the level that a novice C language should possess. The processing is incomplete, and the algorithm is not considerate,CodeToo long and concise. Char * inttostr (INT number) { Char CH, * STR, * t; Int I, Len = 0; STR = (char *) malloc (11 * sizeof (char )); T = STR; While (number! = 0) { * T = (Number % 10) + 0x30; Number = Number/10; Len ++; T ++; } * T = '/0 '; T = STR; For (I = 0; I <Len/2; I ++) { Ch = * t; * T = * (t + Len-2 * i-1 ); * (T + Len-2 * i-1) = CH; T ++; } Return STR; } ××××××××××××××××××××××××××××××××× Algorithm two pointers, first and last interchange   Char * inttostr (INT number) { Char CH, * STR, * right, * left; Unsigned int value; STR = (char *) malloc (12 * sizeof (char )); Left = right = STR; // If it is a negative number, a negative number should be added, and left and right should go backward. If (number <0) { Value =-number; * STR = '-'; Left ++, right ++; } Else Value = (unsigned) number; // Convert a number into a string (inverted) While (value) { * Right = (Value % 10) + 0x30; Value = value/10; Right ++; } * Right -- = '/0 '; // Put the inverted string forward. While (Right> left) { Ch = * left; * Left ++ = * right; * Right -- = CH; } Return STR; } The above functions apply for dynamic space internally. After returning the space to the caller, the caller needs to release the space, which does not meet the coupling characteristics between modules. Therefore, the function prototype is best Char * inttostr (INT number, char * output) The output pointer is the heap or automatically allocated stack area applied by the caller. inttostr can save the converted string.   ××××××××××××××××××××××××××××××××× Algorithm three modulo, from low to high   First, find the number of digits of the current integer in decimal format, calculate the modulo of the address stored after the swap bit conversion, and retrieve the swap bit and store it from the high address to the low address. The advantage is that you do not need to flip the string. Char * up_str_from_ I (INT I _in, char * str_out) { Int t_ I _in; Int t_num_count = 0; Char * back = str_out; If (I _in <0) { I _in * = (-1 ); * Str_out ++ = '-'; }   T_ I _in = I _in; While (t_ I _in/= 10) T_num_count ++; // First obtain the number of digits in decimal format of the current integer, and calculate the address after the second-digit conversion. // Evaluate the modulo and retrieve the bitwise from the high address to the low address. The advantage is that you do not need to flip the string. Str_out + = t_num_count; Str_out ++; * Str_out = '/0 '; Str_out --; Do { * Str_out = I _in % 10 + '0 '; If (I _in/= 10) Str_out --; // If there r some num forword, so str_out go back } While (I _in % 10); // If there r some num, so Loop   Return back; }   ××××××××××××××××××××××××××××××××× Algorithm 4 remainder, from high to low First, find the number of digits of the current integer in decimal format. Calculate the number devide_num that the highest bit should be divided by when the remainder is obtained. Then, divide devide_num by 10 each time and retrieve the remainder from high to low, from low address to high address storage, the advantage is that you do not need to flip the string Char * down_str_from_ I (INT I _in, char * str_out) { Int t_ I _in; Unsigned int devide_num = 1; Char * back = str_out; If (I _in <0) { I _in * = (-1 ); * Str_out ++ = '-'; }   T_ I _in = I _in; While (t_ I _in/= 10) Devide_num * = 10; // updating devide_num by multiplying 10 Printf ("the absolute integer is % d, and devide_num is % d/N", I _in, devide_num );   While (I _in/10) { * Str_out ++ = I _in/devide_num + '0 '; I _in % = devide_num; Devide_num/= 10; // Update the divisor and Divisor } * Str_out ++ = I _in + '0'; // single digit * Str_out ++ = '/0 ';   Return back; }   ××××××××××××××××××××××××××××××××× Algorithm 5 recursive search for high positions   Char * rcsv_str_from_ I (INT I _in, char * str_out) { // Static unsigned COUNT = 0; // In case it is a minor integer for the first time If (I _in <0) { I _in * = (-1 ); * Str_out ++ = '-'; } If (I _in/10) // not the most important bit in decimal, then recursively calling itself { Str_out = rcsv_str_from_ I (I _in/10, str_out ); * Str_out ++ = I _in % 10 + '0 '; * Str_out = '/0'; // in case this is the last step } Else // The most important bit { * Str_out ++ = I _in + '0 '; * Str_out = '/0'; // in case this is the last step } // Return the address for the next valid char Return str_out; }

Int main (void)

{

Int I;

Char str_out [100];

While (1)

{

Scanf ("% d", & I );

Printf ("up method gets % s/n", up_str_from_ I (I, str_out ));

Printf ("down method gets % s/n", down_str_from_ I (I, str_out ));

Rcsv_str_from_ I (I, str_out );

Printf ("recursive method gets % s/n", str_out );

 

}

Return 0;

}

This recursive algorithm is derived from the above down method. The nature of the down method is to find the highest bits, and then retrieve them from the highest bits, store them in the order of arrays, without the need to flip the string. Therefore, the condition for recursion is that the current number is greater than 10, that is, the maximum bit is not reached. The condition for Recursive exit is that the current number of digits indicates that the maximum bit is found. When you exit, you must pass the modified pointer value to the upper-layer caller. After each layer exits recursively, you need to save the single digit and exit upwards to convert the last digit of the initial number.   The disadvantage of the current recursive method is that the chain operation cannot be implemented, that is, the pointer value returned in the last time is not the value passed by the function caller. I want to save the number of conversions using the static variable, at the end of the recursion exit, the returned pointer is reduced to the original pointer value. After all, this problem is not serious during the interview. If you are not thinking deeply, you can try it.   Other better methods are available for discussion! ××××××××××××××××××××××××××××××××× References: Http://blog.csdn.net/ammana_babi/archive/2006/07/18/936918.aspx Http://blog.csdn.net/kimn/archive/2005/01/14/253434.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.