Gamestabled

leetcode 10/17/2024

Oct 17th, 2024
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. #include <ranges>
  2.  
  3. constexpr long long pow(int num, int power) {
  4. if (power == 0) return 1;
  5. return (long long)num * pow(num, power - 1);
  6. }
  7.  
  8. constexpr int ithDigit(int num, int i) {
  9. return (num / pow(10, i)) % 10;
  10. }
  11.  
  12. static_assert(ithDigit(1234, 0) == 4);
  13. static_assert(ithDigit(1234, 1) == 3);
  14. static_assert(ithDigit(1234, 2) == 2);
  15. static_assert(ithDigit(1234, 3) == 1);
  16.  
  17. constexpr int numDigits(int num) {
  18. if (num == 0) return 0;
  19. return 1 + numDigits(num / 10);
  20. }
  21.  
  22. static_assert(numDigits(1) == 1);
  23. static_assert(numDigits(12) == 2);
  24. static_assert(numDigits(123) == 3);
  25. static_assert(numDigits(1234) == 4);
  26.  
  27. constexpr int swapDigits(int num, int a, int b) {
  28. long long int firstValue = ithDigit(num, a) * (long long) pow(10, a);
  29. long long int secondValue = ithDigit(num, b) * (long long) pow(10, b);
  30. int removedSwaps = num - firstValue - secondValue;
  31. long long int newFirst = ithDigit(num, a) * (long long) pow(10, b);
  32. long long int newSecond = ithDigit(num, b) * (long long) pow(10, a);
  33. return removedSwaps + newFirst + newSecond;
  34. }
  35.  
  36. static_assert(swapDigits(1234, 0, 1) == 1243);
  37. static_assert(swapDigits(1234, 2, 3) == 2134);
  38. static_assert(swapDigits(1234, 0, 3) == 4231);
  39. static_assert(swapDigits(1234, 2, 1) == 1324);
  40.  
  41. class Solution {
  42. public:
  43. constexpr int maximumSwap(int num) {
  44.  
  45. int num_digits = numDigits(num);
  46.  
  47. auto all_possibilites = std::views::cartesian_product(std::views::iota(0, num_digits),
  48. std::views::iota(0, num_digits)) |
  49. std::views::transform([num](std::tuple<int, int> t) {
  50. const auto& [a, b] = t;
  51. return swapDigits(num, a, b);
  52. });
  53.  
  54. return std::ranges::max(all_possibilites);
  55. }
  56. };
  57.  
Advertisement
Add Comment
Please, Sign In to add comment