Please let me know solution to these 2 problems of ‘time to try’. Solution is not available.
Solution is not there?
Hey @anuj_it
Method
- If x is less than y, swap the two variables value
- Recursively find y times the sum of x
- If any of them become zero, return 0
Code
function:
int
product(
int
x,
int
y)
{
// if x is less than
// y swap the numbers
if
(x < y)
return
product(y, x);
// iteratively calculate
// y times sum of x
else
if
(y != 0)
return
(x + product(x, y - 1));
// if any of the two numbers is
// zero return zero
else
return
0;
}
@anuj_it
Approach:
Write a recursive function that will take the first digit of the string and multiply it with the appropriate power of 10 and then add the recursive result for the substring starting at the second index. The termination condition will be when the passed string consists of a single digit. In that case, return the digit represented by the string.
Code:
int
stringToInt(string str)
{
// If the number represented as a string
// contains only a single digit
// then returns its value
if
(str.length() == 1)
return
(str[0] -
'0'
);
// Recursive call for the sub-string
// starting at the second character
double
y = stringToInt(str.substr(1));
// First digit of the number
double
x = str[0] -
'0'
;
// First digit multiplied by the
// appropriate power of 10 and then
// add the recursive result
// For example, xy = ((x * 10) + y)
x = x *
pow
(10, str.length() - 1) + y;
return
int
(x);
}
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.