recursive problem
Aug 21, 2013 at 6:49pm UTC
1 2 3 4 5 6 7 8 9 10
int sub(string &temp,int begin,int end){
if (end-begin == 0){
return temp[begin];
}else {
return sub(temp,begin+1,end) + temp[begin];}
}
i want to add all subset elements
but when i do
cout << sub(5) << endl;
it print 150.... wtf
Aug 21, 2013 at 6:53pm UTC
cout << sub(5) << endl;
Shouldn't compile unless you have another overloaded version of sub .
Aug 21, 2013 at 6:54pm UTC
yea i know... i just minimize the cout
string x = "123";
cout << sub(x,0,x.size()-1)<<endl;
if you want
Aug 21, 2013 at 7:05pm UTC
150 is the correct output for:
1 2
string x = "123" ;
cout << sub(x,0,x.size()-1)<<endl;
Perhaps you wanted it to calculate 1 + 2 + 3 rather than '1' + '2' + '3' ?
Aug 21, 2013 at 7:12pm UTC
oh ok
so how do u write for the
return sub(temp,begin+1,end) + temp[begin]
part?
Aug 21, 2013 at 7:16pm UTC
i tried int and * but not sure
Aug 21, 2013 at 7:21pm UTC
You can convert a single character that is also a digit to it's numerical value by subtracting '0' from the character.
1 2 3 4 5 6 7 8 9
int sub(string &temp,int begin,int end)
{
int value = temp[begin] - '0' ;
if ( end == begin )
return value ;
return sub(temp, begin+1, end) + value ;
}
Aug 21, 2013 at 7:24pm UTC
that is really helpful
thak you cire
Aug 21, 2013 at 7:30pm UTC
1 2 3 4
int sub( const std::string &s, std::string::size_type pos, std::string::size_type n )
{
return ( n == 0 ? 0 : s[pos] - '0' + sub( s, pos + 1, n - 1 ) );
}
Topic archived. No new replies allowed.