Convert a number from base 10 to N
java
Solution
Flip the order of the first 2 lines in the loop; by doing the division first, you lose the first remainder. But then you'll need to handle the last remainder.
Problem
This code is a part of a project that I have to develop. I need to write a java method that converts a number (base 10) to another number in `n` base. This is the code of the class: ``` public class converter { public int from_10_to_n(int base, int newbase) { int k = 0; String res = ""; String output = ""; do { //Below I explain what I'm doing here base /= newbase; k = base % newbase; res += String.valueOf(k); } while (base != 0); for(int i=res.length()-1; i>-1; i--) { output += res.charAt(i); } return Integer.parseInt(output); } ``` I thought to make the program in this way: The `do {} while();` loop divides the numbers and saves in k the remainders. Then I make a for loop that reverses the string res (which has the reminders). By the way when I call the method in my main, I am missing the last digit. I mean: ``` converter k = new converter(); int e = k.from_10_to_n(a /*base 10 number*/, b /*Base n number*/); System.out.println(a+" -> "+b+" is " + e); ``` With this code, if I want to convert 231 to base 4 I have `321` as result instead of `3213`. I have checked my code but I cannot find a solution. Any idea? I have the same error with other bases. For example 31 (base 10) is `11111` (base 2) but my program returns `1111`.