Search code examples
c++decimalradixternary

Collecting remainders while converting a number to ternary base ( C++ )


I am trying to write a program in C++. It's a much longer program, but I need help regarding just one of the functions in it.

Basically, this function should get a number, and then return that same number but in ternary base. Now, my idea is to basically divide that number by 3 and collect remainders ( if my number is "n", I'd use n%3) and then I would just divide that number with 3 ( n/3 ) and go again until that number "n" by repeated division becomes 0.

This should work and convert the number to ternary base, but my problem is the fact that I do not know how to collect these remainders. This is probably a stupid question, but I am still a begginer in programming.

Basically, if I make a while loop , something like this :

while(n>0) 
{
 int digitofternary=n%3;
 n/=3;
}

In every iteration of while loop, digitofternary is just going to change. How can I adjust this loop so digits get remembered/collected and I can return a new normal ternary base number from function?

Sorry if this sounded confusing, hope it didn't ( I am not a native english speaker ).


Solution

  • int sample_fn (int n) 
    { 
        std::string str_ret;
        while(n>0) 
        {
           int digitofternary=n%3;
           n/=3;
           std::string str= std::to_string(digitofternary);
           str_ret.append(str); 
        }
        return std::stoi(str_ret);
    }