Getting each individual digit from a whole integer

后端 未结 9 1223
南方客
南方客 2020-11-30 04:05

Let\'s say I have an integer called \'score\', that looks like this:

int score = 1529587;

Now what I want to do is get each digit 1, 5, 2,

9条回答
  •  时光取名叫无心
    2020-11-30 04:26

    This solution gives correct results over the entire range [0,UINT_MAX] without requiring digits to be buffered.

    It also works for wider types or signed types (with positive values) with appropriate type changes.

    This kind of approach is particularly useful on tiny environments (e.g. Arduino bootloader) because it doesn't end up pulling in all the printf() bloat (when printf() isn't used for demo output) and uses very little RAM. You can get a look at value just by blinking a single led :)

    #include 
    #include 
    
    int
    main (void)
    {
      unsigned int score = 42;   // Works for score in [0, UINT_MAX]
    
      printf ("score via printf:     %u\n", score);   // For validation
    
      printf ("score digit by digit: ");
      unsigned int div = 1;
      unsigned int digit_count = 1;
      while ( div <= score / 10 ) {
        digit_count++;
        div *= 10;
      }
      while ( digit_count > 0 ) {
        printf ("%d", score / div);
        score %= div;
        div /= 10;
        digit_count--;
      }
      printf ("\n");
    
      return 0;
    }
    

提交回复
热议问题