Split a integer into its separate digits

后端 未结 3 1052
生来不讨喜
生来不讨喜 2020-12-30 16:05

Say I have an integer, 9802, is there a way I can split that value in the four individual digits : 9, 8, 0 & 2 ?

相关标签:
3条回答
  • 2020-12-30 16:43

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

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

    This spits out the digits from least-significant to most-significant. You can clearly generalise this to any number base.

    0 讨论(0)
  • 2020-12-30 16:49

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

    Something like:

    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.

    0 讨论(0)
  • 2020-12-30 17:00

    if you need to display the digits in the same order you will need to do the module twice visa verse this is the code doing that:

    #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;
    }
    

    i hope that it is useful :)

    0 讨论(0)
提交回复
热议问题