Recursive Algorithm for integer Inversion

Source: Internet
Author: User

Question: reverse the integer and save the result to an integer array, for example:

Input: 12345

Output: [5, 4, 3, 2, 1]

 

1 # include "stdafx. h"
2 # include <iostream>
3 using namespace std;
4 # define INT_LENGTH 20
5
6 // reverse the integer
7 // The integer to be reversed in the n input
8 // result: the array pointer for storing the result
9 // the return value of the int type indicates the depth of recursion, that is, the number of digits of an integer.
10 int ReverseInteger (int n, int * result)
11 {
12 * result ++ = n % 10;
13 if (n/10 = 0)
14 {
15 return 1;
16}
17 else
18 {
19 return 1 + ReverseInteger (n/10, result );
20}
21}
22
23 // print the result
24 void PrintResult (int * result, int len ){
25 for (int I = 0; I <len; I ++)
26 cout <result [I] <"";
27}
28
29 int _ tmain (int argc, _ TCHAR * argv [])
30 {
31 int n = 123405;
32 // Initialization
33 int * result = new int [INT_LENGTH];
34 for (int I = 0; I <INT_LENGTH; I ++)
35 result [I] = 0;
36
37 int len = ReverseInteger (n, result );
38
39 PrintResult (result, len );
40
41 delete [] result;
42 return 0;
43}

 

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.