fork(1) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4.  
  5. uint64_t CompressAmount(uint64_t n)
  6. {
  7. if (n == 0)
  8. return 0;
  9. int e = 0;
  10. while (((n % 10) == 0) && e < 9) {
  11. n /= 10;
  12. e++;
  13. }
  14. if (e < 9) {
  15. int d = (n % 10);
  16. //assert(d >= 1 && d <= 9);
  17. n /= 10;
  18. return 1 + (n*9 + d - 1)*10 + e;
  19. } else {
  20. return 1 + (n - 1)*10 + 9;
  21. }
  22. }
  23.  
  24. uint64_t DecompressAmount(uint64_t x)
  25. {
  26. // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
  27. if (x == 0)
  28. return 0;
  29. x--;
  30. // x = 10*(9*n + d - 1) + e
  31. int e = x % 10;
  32. x /= 10;
  33. uint64_t n = 0;
  34. if (e < 9) {
  35. // x = 9*n + d - 1
  36. int d = (x % 9) + 1;
  37. x /= 9;
  38. // x = n
  39. n = x*10 + d;
  40. } else {
  41. n = x+1;
  42. }
  43. while (e) {
  44. n *= 10;
  45. e--;
  46. }
  47. return n;
  48. }
  49.  
  50. int main() {
  51. int64_t COIN = 100000000;
  52. int64_t MAX_MONEY = 21000000 * COIN;
  53.  
  54. uint64_t input = MAX_MONEY + 1;
  55. uint64_t result = CompressAmount(input);
  56. uint64_t result2 = DecompressAmount(result);
  57.  
  58. std::cout << "Input : " << input << "\n";
  59. std::cout << "Encoded: " << result << "\n";
  60. std::cout << "Decoded: " << result2 << "\n";
  61. return 0;
  62. }
  63.  
Success #stdin #stdout 0s 4312KB
stdin
Standard input is empty
stdout
Input  : 2100000000000001
Encoded: 18900000000000001
Decoded: 2100000000000001