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
.
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.
The problem lies here:
base /= newbase;
k = base % newbase;
Try this with some real numbers, like 231 and base 4 in your example.
base /= newbase
Now base
is 57 and your k
will be incorrect. You should get the remainder first, then divide:
k = base % newbase;
base /= newbase;
There are also some style problems with your code which you should consider correcting:
base
doesn't really hold any base, just input value - maybe rename it to input
or something like that?If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With