Divide an integer into separate digits

Let's say I have an integer, 9802, is there a way to divide this value into four separate digits: 9, 8, 0, and 2?

+5
source share
3 answers

Keep doing modulo-10 and divide-by-10:

int n; // from somewhere
while (n) { digit = n % 10; n /= 10; }

This spills out numbers from the least significant to the most significant. You can clearly generalize this to any number base.

+22
source

You probably want to use mod and divide to get these numbers.

Sort of:

Grab first digit:

   Parse digit: 9802 mod 10 = 2
   Remove digit: (int)(9802 / 10) = 980

Grab second digit:

   Parse digit: 980 mod 10 = 0
   Remove digit: (int)(980 / 10) = 98

Something like that.

+2
source

, , , :

#import <Foundation/Foundation.h>
int main (int argc, char * argv[])
  {
    @autoreleasepool {
    int number1,  number2=0 ,  right_digit , count=0;
    NSLog (@"Enter your number.");
    scanf ("%i", &number);
   do {
      right_digit = number1 % 10;
      number1 /= 10;
     For(int i=0 ;i<count; i++)
        {
        right_digit = right_digit*10;
        }
   Number2+= right_digit;
   Count++;
      }
  while ( number != 0 );
do {
right_digit = number2 % 10;
number2 /= 10;
Nslog(@"digit = %i", number2);
}
while ( number != 0 );
}
}
return 0;
}

, :)

0

All Articles