Homework help Recursive Function

Write a recursive function for converting a string of digits into the integers it represents. For example, “13531” represents the integer 13,531.

what I have done is below.


void digitToInt(string number);

int main()
{
digitToInt(13531);
}

void digitToInt(string number)
{
if(number.length() == 1)
{
return number.at;
}
else
{
int c = number.at(number.length()-1);
return c + 10 * digitToInt(number.substr(0,number.length()-1))
}
}

i am returning an error overload.
Last edited on
closed account (2UD8vCM9)
Please use code tags, because it's a lot easier to read.

Well one issue is that digitToInt is a function of type void and it should be a function of type int.

You'll have to change your prototype and function definition from void to int like this for example
int digitToInt(string number);

Another issue with your code is in main you aren't setting anything to be what your digitToInt(13531); is returning.

You should be doing something like

 
int digitAsInt = digitToInt(13531);


in your main.

Another issue with the code you posted is int main doesn't return anything. (However, this is irrelevant to your current issue.)



Edit:

Also
return number.at;

I don't believe you can do it this way.

You should do either

return number.at(0);
or
return number[0];

That being said, you are returning the character value with this approach.

To get the integer value, you have to subtract '0' from each character.

See
http://www.asciitable.com/
Last edited on
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
26

int digitToInt(string number);

int main()
{

    int digitasint = digitToInt("13531");
    cout << digitasint;

    system("pause");
    return 0;
}

int digitToInt(string number)
{
	if(number.length() == 1)
	{
	    return number.at(0) -char(48);
	}
	else
	{
	    
	    int c = number.at(number.length()-1) -char(48);
	    return c + 10 * digitToInt(number.substr(0,number.length()-1));
	}
}


I use to program in java so im not sure if in c++ I could say -48 for the ascii value of 0?

I now return inside main

13531
Last edited on
> I use to program in java so im not sure if in c++ I could say -48 for the ascii value of 0?

No, not in portable code. The values of characters are locale specific.
In C++, for the value of character '0' (as an integer), just say '0'

To follow the recursion, put in a few display statements.
('printf debugging' is usually more revealing than unprincipled hacking with a debugger.)

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <string>
#include <cctype>

int char_to_int( char c ) // convert character '0', '1', ... '9' to int
{
    // http://en.cppreference.com/w/cpp/string/byte/isdigit
    if( !std::isdigit(c) ) return 0 ; // character is not a decimal digit

    // characters '0', '1', ... '9' have consecutive values
    // '4' - '0' == 0    '7' - '0' == 7 etc.
    return c - '0' ;
}

static int depth = 0 ;

// invariant: string contains only decimal digits with no leading sign
// assumes that there would not be an integer overflow
int string_to_int( std::string str )
{
    for( int i = 0 ; i < depth ; ++i ) std::cout << "  " ;
    ++depth ;
    std::cout << "str: " << str ;

    if( str.empty() ) return 0 ;

    if( str.size() == 1 )
    {
        const int value = char_to_int( str[0] ) ;
        std::cout << "  => return " << value << '\n' ;
        --depth ;
        return value ;
    }

    // http://en.cppreference.com/w/cpp/string/basic_string/back
    const int last_digit = char_to_int( str.back() ) ;
    std::cout << "  last digit: " << last_digit  << ' ' ;

    // http://en.cppreference.com/w/cpp/string/basic_string/pop_back
    str.pop_back() ; // digits except the last digit
    std::cout << "  remaining: " << str << '\n' ;

    const int value_of_remaining_digits = string_to_int(str) ;
    const int value = value_of_remaining_digits * 10 + last_digit ;

    --depth ;
    for( int i = 0 ; i < depth ; ++i ) std::cout << "  " ;
    std::cout << value_of_remaining_digits << " * 10 + " << last_digit
              << " == " << value << "  => return " << value << '\n' ;

    return value ;
}

int main()
{
    for( std::string str : { "1234", "567", "987654" } )
    {
        depth = 0 ;
        std::cout << str << '\n' ;
        std::cout << string_to_int(str) << "\n------------------\n\n" ;
    }
}

http://coliru.stacked-crooked.com/a/6a3361f74cd70ca4
ahh, i see. So in c++ i can literally return the character value 0. I have done so this way and now i am returning the correct values. However, with my recursive function i have no idea how i would go about inserting my ",". Would i start at the tail and work towards the head? Here is my code.

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
int digitToInt(string number);

int main()
{

    int digitasint = digitToInt("13531");
    cout << digitasint;

    system("pause");
    return 0;
}

int digitToInt(string number)
{
	if(number.length() == 1)
	{
	    return number.at(0) - '0';
	}
	else
	{
	    
	    int c = number.at(number.length()-1) - '0';
	    return c + 10 * digitToInt(number.substr(0,number.length()-1));
	}
}


returns:

13531
> i have no idea how i would go about inserting my ","

Where do you want to insert commas?

To punctuate printed numbers with embedded commas:

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
26
27
28
29
30
31
#include <iostream>
#include <locale>
#include <string>

int main()
{
    // http://en.cppreference.com/w/cpp/locale/numpunct
    struct numpunct_with_commas : std::numpunct<char>
    {
        protected:
            virtual std::string do_grouping() const override
            {
                // three digits in the right-most group, two digits in each group to the left
                static const std::string grouping = "\3\2" ;
                return grouping ;
            }

            virtual char do_thousands_sep() const override
            { return ',' ; } // use a comma as the group separator
    };

    const int n = 123456789 ;
    std::cout << n << '\n' ;

    // http://en.cppreference.com/w/cpp/io/basic_ios/imbue
    // http://en.cppreference.com/w/cpp/locale/locale/locale
    // note: ownership of the facet is handed over to the locale.
    // deleting the facet is its responsibility
    std::cout.imbue( std::locale( std::cout.getloc(), new numpunct_with_commas ) );
    std::cout << n << '\n' ;
}

http://coliru.stacked-crooked.com/a/aacd9d19ce4d4cfe
Topic archived. No new replies allowed.