I need to create a recursive function which replaces all odd digits to a 4.
Example
User enters: 2391
Output: 2444
Please use beginner C++ language, no array and etc. Using basic C++ language and recursive would be truly helpful thanks.
int oddToFour(int num) {
int digit = num % 10;
if (digit / 2 != 0) return 4;
else return digit;
oddToFour(num/10);
}
The following code should work:
int oddToFour(int num) {
if (num == 0)
return 0;
int digit = num % 10;
if (digit % 2 == 1)
digit = 4;
return oddToFour(num/10) * 10 + digit;
}
Hope you find it helpful.
Related
I need to make a simple function in c++ that will say if an entered integer has its digits ascending from left to right. Ex, 123 is ascending. We just started learning recurssion, which is what I'm supposed to use, but I'm confused. So far what I was thinking is that you store the last digit as a temp, then compare that to the next digit, but how would you manage to do that?
bool ascending(int n) {
int temp = n % 10;
while (n / 10 > 0) {
n = n / 10;
if (temp > n % 10) {
return false;
break;
}
temp = n % 10;
}
}
This is the code I have so far, but I'm definitely messing up. I'm not even using recurrsion.
Here is one way you can go about it.
On every iteration, you check that last 2 digits are in order. And when the number is a single digit, return true
bool ascending(int n) {
int last_digit = n % 10;
int remainder = n / 10;
if (remainder == 0)
{
return true;
}
int second_last_digit = remainder % 10;
if (last_digit < second_last_digit)
{
return false;
}
else
{
return ascending(remainder); // Recusrive call
}
}
I need to create a recursive function that counts the 2 and 6 from the number a user inputs.
For example if the user enters 26827 the count is 3.
It works with certain numbers and certain numbers it doesn't. Can someone please modify my function making sure its recursive and using very basic C++ language as I have used. Thank you! (I believe something is wrong with return type.)
int count(int n) {
static int count = 0;
if (n == 2 || n == 6) count++;
if ((n % 10 == 2) || (n % 10 == 6)) {
count++;
count(num / 10);
}
else return count;
}
One liner for fun.
int f(int n) {
return n == 0 ? 0 : (n%10==2 || n%10==6) + f(n/10);
}
int count(int n) {
if(n <= 0) return 0; // Base Condition
int countDig = 0; // Initalizing Count of digits
if(n % 10 == 2 || n % 10 == 6) // Checking whether the LSB is 2 or 6
countDig ++; // If it is then incrementing the countDig
countDig += count(n / 10); // Calling the recurive function by sending the number except its LSB
//And incrementing counter according to it
return countDig; // Returning the final count
}
you don't need to have a static value counter. It can be easily done as above. Please refer to comments given. Second the error in your code is you only calling the recursion if the LSB is 2 or 6. The recursion should be put outside the if condition in your code. Why are you using num variable. I think it should be n
You don't need statics
This should work (note return c + count(n / 10) line. That's the main recursion here)
int count(int n)
{
int c = 0;
if(n % 10 == 2 || n % 10 == 6)
c = 1;
if(n < 10)
return c;
return c + count(n / 10);
}
If you want to make it with recursion , another procedure you can apply using string manipulation.
PseudoCode:
Function ( int n):
1. Make n as a string. ( Convert Number to string)
2. Collect the first character (char C) of the string and remove the character from the string.
3. Make the main string again as a number n. ( Convert String to Number).
4. Check the character C , which is number 2 or 6 or not, count it with a flag.
5. Enter base case for which the recursion will stop.
6. return the number n , inside the Function (n) for recursion.
I am using a Constructor to take an unsigned int as an argument, break it into digits and assign the appropriate true and false values to a vector object. But the problem is that, my poor logic assigns the values in reverse order as the last digit is separated first and so on. The Code I have written is:
vector<bool> _bits;
uBinary(unsigned int num){
int i = 1;
while(num > 0)
{
int d = num%10;
num /= 10;
_bits.resize(i++);
if(d == 1)
{
_bits[_bits.size() - 1] = true;
}
else if(d==0)
{
_bits[_bits.size() - 1] = false;
}
}
}
For example: if argument 10011 is passed to the function uBinary() the vector object will be assigned the values in this order 11001 or true,true,false,false,true which is reversed.
All I need to do here is that, I want to assign the values without reversing the order and I don't want to use another loop for this purpose.
One way is to start at the highest possible digit (unsigned int can only hold values up to 4294967295 on most platforms) and ignore leading zeros until the first actual digit is found:
for (uint32_t divisor = 1000000000; divisor != 0; divisor /= 10) {
uint32_t digit = num / divisor % 10;
if (digit == 0 && _bits.size() == 0 && divisor != 1)
continue; // ignore leading zeros
_bits.push_back(digit == 1);
}
But finding the digits in reverse and then simply reversing them is much simpler (and at least as efficient):
do {
_bits.push_back(num % 10 == 1);
num /= 10;
} while (num != 0);
std::reverse(_bits.begin(), _bits.end());
One way you can do the reversing with another loop or std::reverse is to use recursion. With recursion you can walk down the int until you hit the last digit and then you add the values to the vector as the calls return. That would look like
void uBinary(unsigned int num)
{
if (num == 0)
return;
uBinary(num / 10);
_bits.push_back(num % 10 ? true : false);
}
Which you can see working with
int main()
{
uBinary(10110);
for (auto e : _bits)
std::cout << e << " ";
}
Live Example
Do note that it is advisable not to use leading underscores in variables names. Some names are reserved for the implementation and if you use one it is undefined behavior. For a full explanation of underscores in names see: What are the rules about using an underscore in a C++ identifier?
i'm trying to do a subtraction of digits in a recursive way, lets say that I have the number 125 then the subtraction takes place doing it this way
5-2-1 = 2
I've already done the sum with recursion but i'm stuck thinking about it because i'm trying to get each digit and then subtract it within the function itself this way
int RecursiveMath::restaDigitos(int n){
if(n/10 <= 1){
return 0;
}else{
return restaDigitos(n/10) - n%10;
}
}
I do know this function is not working but it's what i've tried along with many combinations, I feel like i'm complicating it too much, any help/advice would be highly appreciated!
You can simplify the task because 5 - 2 - 1 is equal to 5 - (2 + 1), so we can sum up all digits except highest, and subtract this sum from it.
int subtractDigits(const unsigned int n, const bool first = true){
if(n == 0){
return 0;
}
if(first){
return n % 10 - subtractDigits(n / 10, false);
}
else{
return n % 10 + subtractDigits(n / 10, false);
}
}
AHHH This one was tricky
#include <stdio.h>
int restaDigitos(int n){
printf("Processing: %d\n", n);
printf("division: %d\n", n/10);
if(n==0){
return 0;
}else{
return n%10 + restaDigitos(n/10);
}
}
int main() {
int input = 125;
int firstVal = input % 10;
int result = restaDigitos(input / 10);
printf("result: %d\n", firstVal - result);
}
Two major corrections were made:
Your termination condition was neglecting the last case where a single digit remains so it terminated early
The first value cannot be recursive because it is positive. (5-2-1) -> The first number 5 is positive whereas the other values are negative
Hope this helped!
The problem is that you are also subtracting the last number (0 - 1 -2 - 5), but from what I can tell from your question, you want to add it (0 - 1 -2 + 5). My solution is to add another argument specifying the number of digits so that you know when to add instead of subtract
int RecursiveMath::restaDigitos(int n, int numDigits){
if (n == 0) {
return 0;
} else if (n / (pow(10, numDigits - 1)) >= 1){
return restaDigitos(n/10, numDigits) + n % 10;
} else {
return restaDigitos(n / 10, numDigits) - n % 10;
}
}
You are processing the first value differently that the others. Such a use case leads to tricky recursion ways, using default parameters or static values for one shot solutions.
Here you could use:
int restaDigitos(int val, bool first = true, int curr = 0) {
if (val == 0) return curr;
if (first) curr = val%10;
else curr -= val%10;
return restaDigitos(val/10, false, curr);
}
You can control that restaDigitos(125); gives as expected 2.
Write a recursive function to check how many digits in the number can be divided by the digit which is after them. Example: 84963 should return 2, because 8 can be divided by 4 and 6 can be divided by 3. My function doesnt seem to output anything at all.
#include <iostream>
using namespace std;
int fun (int n);
int main()
{
int n;
cin >> n;
cout << fun(n) << endl;
return 0;
}
int fun(int n){
int count = 0;
if (fun(n % 100) % fun(n % 10) == 0)
count++;
return count;
}
Your recursion does not make much sense at the moment. A more logical approach to this would be to see if the last number (so 1 in 321), can currently divide the second last number (so 2 in 321). You could do this by defining a function that checks if that is possible, and recursively passes on the number divided by 10. That function would look something like this:
int fun(int n)
{
if (n < 10)
return 0;
int last = n % 10;
n = n / 10;
int secondlast = n % 10;
if (secondlast != 0 && last != 0 && secondlast % last == 0)
return 1 + fun(n);
else
return fun(n);
}
Update note: After looking into Vlad from moscow's comment, I moved the last != 0 part of the condition forward, to solve a bug (divide by 0).
The problem Vlad from moscow was talking about is the following: If you want, for example, the part 04 to count as 0, you should use the code as it is above. Otherwise you should remove the secondlast != 0 part.
int countIfDiv(int num) {
int pair = num % 100;
int first = pair / 10;
if (first == 0) return 0;
int second = pair % 10;
int next = num / 10;
return first % second == 0 ? 1 + countIfDiv(next) : 0 + countIfDiv(next);
}
Just pull a pair, try the division, then chop the last number and repeat.
You're not actually updating n value so you get into an infinite loop, on the other hand, your function is, initially, only designed for 3 digits number. I think that it should be something similar to:
int fun(int n, int ant, int count){
if( n == 0 )
return count;
if (ant != 0 &&
(n%10) % ant == 0)
count++;
return fun(n/10, n%10, count);
}
I should work with different number of digits.
The valid code will be
size_t fun( int n )
{
const int base = 10;
int digit = n % base;
n /= base;
return ( n == 0 ?
0 :
( digit && n % base && !( n % base % digit ) ) + fun( n ) );
}