0

I was doing this challenge:

Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.

I tried to avoid using sorting so I made this:

#include <math.h>
#include <iostream>

int main()
{
  uint64_t a = 1234567889;
  uint64_t result = 0;
  int stupid_idea[10] = {0};
  
  //This counts the number of digits
  while (a > 0){
    stupid_idea[a%10] += 1;
    a = a/10;
  }

  
  //This (should) use the numbers of digits to then order them
  for (int i=9;i>=0;i--){
    int power = pow(10,stupid_idea[i]);
    //This is here so you can see pow (debuggin)
    std::cout << power << '\n';
    result *= power;
    result += i*((power-1)/9);
  }
  
  std::cout << result;
  return 0;
}

The final result should be:

9887654321

I am actually getting:

9717654321

The problem seems to be pow(10,stupid_idea[i]) which is giving me 99 in a case and I don't know how 10x can be 99.

Compiler version:

win32 gcc 9.2.0

Compile command:

c++ main.cpp

Log:

10
99
10
10
10
10
10
10
10
1
9717654321
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 4
    `pow` is for floating-point and now you're seeing why it is not a good idea to use for integers. pow(10,2)` might return `99.999999999`, which is pretty close, but converting to `int` truncates the fractional part. – Nate Eldredge May 12 '21 at 22:41
  • 1
    This is because `pow(10,x)`, when used with integers, does not raise 10 to the given power. That's not what it does. Unfortunately this is not really explained on websites that have lists of largely meaningless programming puzzles. To learn what various C++ library functions do, and how that work, that information can only be found in a quality C++ textbook. A basic algorithms textbook will also likely have an algorithms to do the given task using integer math only, without `pow` or anything of that sort... – Sam Varshavchik May 12 '21 at 22:43
  • 3
    See [What is the correct way to raise an integer to a positive integer power in C++?](https://stackoverflow.com/questions/12562408/what-is-the-correct-way-to-raise-an-integer-to-a-positive-integer-power-in-c) – Nate Eldredge May 12 '21 at 22:43
  • 1
    try `int power = round(pow(10,stupid_idea[i]));` -- you want to round to the nearest integer rather than truncating towards 0. – Chris Dodd May 12 '21 at 22:46
  • 2
    Just do integer math: `result = result * 10 + stupid_idea[i];`. – Pete Becker May 12 '21 at 23:06
  • [Why does pow(5,2) become 24?](https://stackoverflow.com/q/22264236/995714), [Why pow(10,5) = 9,999 in C++](https://stackoverflow.com/q/9704195/995714), [Why the result of pow(10,2) 99 instead of 100?](https://stackoverflow.com/q/54057687/995714) – phuclv May 13 '21 at 02:45

0 Answers0