Sorting digits of an integer

前端 未结 9 1264
日久生厌
日久生厌 2020-12-16 01:26

You are given an integer 51234 (say) we need to sort the digits of a number the output will be 12345.

How to do it without using array ?

9条回答
  •  萌比男神i
    2020-12-16 02:11

    // Bubblesort
    long sortNum(long n) {
      while (true) {
        long a = n % 10, p = 9;
        bool s = false;
        for (long r = n / 10; r; r/= 10) {
          long b = r % 10;
          if (a < b) {
            n -= p * (b - a);
            s = true;
          } else a = b;
          p *= 10;
        }
        if (!s) return n;
      }
    }
    
    #include 
    
    int main(int argc, char **argv) {
      if (argc > 1) {
        long n = strtol(argv[1], 0, 0);
        std::cout << "Unsorted: " << n << std::endl;
        n = sortNum(n);
        std::cout << "Sorted:   " << n << std::endl;
      }
      return 0;
    }
    
    $ g++ -Wall -Wextra bubble-int.cpp && ./a.exe 183974425
    Unsorted: 183974425
    Sorted:   123445789
    

提交回复
热议问题