Shortest and most general way to convert base-10 integers to any base less than 10 ? (C++) -


i'm trying write function takes in 2 parameters: number converted , base of output number.

based on code i've written, converts base-10 integers base-3,

std::string decto3(int x) {     std::string t;     while (x != 0)     {         if (x % 3 == 0)             t = "0" + t;         else if ((x + 2) % 3 == 0)             t = "1" + t;         else t = "2" + t;         x = floor(x / 3);     }     return t; } 

i've went on generalize base-n conversion (n<10)

std::string decton(int x, int n) {     std::string t;     while (x != 0)     {         if (x%n == 0)             t = "0" + t;         else         {             (int = 1; < n;i++)             {                 if ((x + n - i) % n == 0)                      t = ""+ + t;             }         }         x = floor(x / n);     }     return t; } 

but none of tests i've made worked. code barely either returns "0" or nothing @ all. doing wrong here ?


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -