6 lines c++ solution, decimal to nonary conversion


  • 4
    int newInteger(int n) {
        int res = 0, s = 1;
        while (n > 0) {
            res += n % 9 * s;
            n /= 9;
            s *= 10;
        }
        return res;
    }
    

    You may already know binary and decimal where number goes up to a more significant digit when it hits two or ten. e.g. 2^1=>10, 2^2=>100, 2^3=>1000.
    The problem here is almost the same. When it hits 9 it goes up. e.g. 9^1=>10, 9^2=>100, 9^3=>1000, etc. Simply use our math knowledge to convert back making use of division and modulo.


  • 0

    @mzchen: Could you kindly elaborate with some comments? It becomes pretty difficult to understand, given just the code. Thank you in anticipation.


  • 0

    @BatCoder this code converts n (base 10) to n (base 9). I think it is more simple to understand using a string as follows, since appending onto the front of a string already takes into account the current position ( there is no need to multiply by 10 to "left shift" the integer over in order to make space for the next base9 right-most digit ).

    class Solution{
    public:
        int newInteger(int n){
            
            //
            // return n base 9
            //
            string base9 = "";
            
            while ( n > 0){
                
                //
                // right-most base9 digit, add onto the front of the string
                //
                base9 = to_string(n % 9) + base9;
                
                //
                // right-shift n base9, this removes the right-most digit base9
                //
                n /= 9;
            }
            
            return stoi(base9);
        }
    };
    

  • 0
    This post is deleted!

  • 0
    H

    @claytonjwong
    method convertUsingInt is not right, it will output number in reverse order


  • 0
    L

    @mzchen perfect!Amazing idea


  • 0
    V

    @BatCoder Think it this way: you're asked to count n numbers in number system where only digits 0..8 are used(base 9). Now this solution just does that, but keeps base(s in code) 10 as answer required is in decimal.

    This method will not work if we modify problem to remove 8 or say 5.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.