简体   繁体   中英

C Programming Removing digits from an integer

Is it possible to remove a digit from an integer?
For example if I want to remove all even digits from 123658 and be left with
135 how could I do that?

This is for an assignment, I can't use arrays, character variables or Math.h functions.

Here is the code I have written so far

uint32_t phaseInt(uint32_t N, enum ProcessChoice Choice) {

   uint32_t phaseInt = 0;
   uint32_t tempVar = N;

   if (tempVar == 0){
    phaseInt = 0;
   }
   if (tempVar != 0 && Choice == Even){
    while(tempVar != 0)
        {
          tempVar % 10;
           tempVar /= 10;
          if ( tempVar % 2 == 0)
          {
              doSomeAction(tempVar);
          }
        }

   }

For example if I want to remove all even digits from 123658 and be left with 135 how could I do that?
... can't use arrays, character variables or Math.h functions.

OP's code is somewhat close.

phaseInt = 0; reminds me of BASIC. In C, return the value instead.

I am sure a non-recursive solution, something like OP's can be written, yet recursion is so tight here.

Pseudo recursion code to not give it all away

uint32_t PhaseInt_SansEven(uint32_t n) {
  if (has_a_small_value_that_needs_no_recursion_and_can_return_0(n)) {
    return 0;
  }

  uint32_t msdigits = all_digits_except_the_least(n);
  uint32_t lsdigit = the_least_digit(n);

  // If odd digit
  if (test_for_oddness(lsdigit) {
    // How to "append" the left digits and the 1 right one
    return PhaseInt_SansEven(msdigits) * TBD1 + lsdigit;
  } else {
    // How to "append" the left digits and ""
    return PhaseInt_SansEven(msdigits) + TBD2;
  }
}

As @BLUEPIXY commented, an all even digit number needs to return an empty number. Hope 0 is OK.


Or non-recursive

uint32_t PhaseInt_SansEven(uint32_t n) {
  uint32_t odds = 0;
  uint32_t pow10 = TBD1;  // Think ones place
  while (n) {
    uint32_t least_digit = the_least_digit_think_mod(n);
    n = shift_one_decimal_digit_right_think_divide(n);
    if (least_digit%2) {
      odds += pow10 * least_digit;
      pow10 *= TBD; // Make 10x larger
    }
  }
  return odds;
}

I don't see the need to use recursion here, it only complicates stuff -feels good though-, you can use a simple while loop with and if statement:

int digit,input,output = 0,currentFactor=1;
//read input
while(input!=0)
{
    digit = input % 10; //read digit
    input = input / 10; //remove digit from input

    if(digit % 2 == 1) //if digit is odd
    {
        output +=  digit*currentFactor; //add digit to output at the position determined by factor
        currentFactor *= 10; //move the position by one digit (multiply factor by 10)
    }
}
return output;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM