Identify the digits in a given number.

前端 未结 7 697
滥情空心
滥情空心 2020-12-07 03:41

I\'m new to programming, and I\'m stuck at a problem. I want my program to identify the separate digits in a given number, like if I input 4692, it should ident

相关标签:
7条回答
  • 2020-12-07 03:58

    Haven't written C code in year, but this should work.

    int i = 12345;
    
    while( i > 0 ){
       int nextVal = i % 10;
       printf( "%d", nextVal );
       i = i / 10;
    }
    
    0 讨论(0)
  • 2020-12-07 04:03

    Another approach is to have two loops.

    1) First loop: Reverse the number.

    int j = 0;
    while( i ) {
       j *= 10;
       j += i % 10;
       i /= 10;
    }
    

    2) Second loop: Print the numbers from right to left.

    while( j ) {
       std::cout << j % 10 << ' ';
       j /= 10;
    }
    

    This is assuming you want the digits printed from right to left. I noticed there are several solutions here that do not have this assumption. If not, then just the second loop would suffice.

    0 讨论(0)
  • 2020-12-07 04:03

    Here is a simple solution if you want to just print the digits from the number.

    #include <stdio.h>
    /**
    printdigits
    */
    void printDigits(int num) {
    
       char buff[128] = "";
       sprintf(buff, "%d ", num);
       int i = 0;
       while (buff[i] != '\0') {
          printf("%c ", buff[i]);
          i++;
       }
       printf("\n");
    }
    /*
    main function
    */
    int main(int argc, char** argv) {
       int digits = 4321;
       printDigits(digits);
       return 0;
    }
    
    0 讨论(0)
  • 2020-12-07 04:05

    Is it correct

    int main()        
    {
        int number;
        cin>>number;
        int nod=0;
        int same=number;
    
        while(same){
            same/=10;
            nod++;
        }
    
        while(nod--){               
            cout<<(int)number/(int)pow10(nod)%10<<"\t";       
        }
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-07 04:06

    A perfect recursion problem to tackle if you're new to programming...

    4692/1000 = 4

    4692%1000 = 692

    692/100 = 6

    692%100 = 92

    92/10 = 9

    92%10 = 2

    You should get the idea for the loop you should use now, so that it works for any number. :)

    0 讨论(0)
  • 2020-12-07 04:13

    I think the idea is to have non reapeating digits printed (otherwise it would be too simple)... well, you can keep track of the already printed integers without having an array encoding them in another integer.

    some pseudo C, to give you a clue:

    int encoding = 0;
    int d;
    
    while (keep_looking()) {
      d = get_digit();
      if (encoding/(2**d)%2 == 0) {
        print(d);
        encoding += 2**d;
      }
    }
    
    0 讨论(0)
提交回复
热议问题