Convert base number 10 to base number 3

How to convert base number 10 to base number 3 using the int converter (int num) method.

import java.util.Scanner; public class BaseConverter { int answer; int cvt = 0; while (num >= 0) { int i = num / 3; int j = num % 3; String strj = Integer.toString(j); String strcvt = Integer.toString(cvt); strcvt = strj + strcvt; num = i; break; } answer = Integer.parseInt("strcvt"); return answer; } public static void main(String[] agrs) { Scanner in = new Scanner(System.in); System.out.println("Enter a number: "); int number = in.nextInt(); System.out.print(converter(number)); in.close(); } 

This was a compilation completed. But when I tried to run it and entered the number, it showed that java.lang.NumberFormatException: for the input line: "strcvt" I do not know how to fix it. How can I do this without using a string?

+8
java
source share
4 answers

You do not need to use String at all.

Try this instead

 public static long asBase3(int num) { long ret = 0, factor = 1; while (num > 0) { ret += num % 3 * factor; num /= 3; factor *= 10; } return ret; } 

Note: the numbers on the computer are only N-bit, that is 32-bit or 64-bit, that is, they are binary. However, what you can do is create a number that when printed in base 10 will actually appear in base 3.

+7
source share

you are not using the declared variable String strcvt , instead because of the typo error you used as "strcvt"

change

 answer = Integer.parseInt("strcvt"); 

to

 answer = Integer.parseInt(strcvt); 
+3
source share

"base 3 number" and "base 10 number" are the same number. In the int converter(int num) method, you change the number, although you only need to change the view. Take a look at parseInt(String s, int radix) and toString(int i, int radix) , which should help you.

+3
source share

You need to strcvt value of strcvt , not the string strcvt

So you need to remove the double qoutes answer = Integer.parseInt(strcvt); And define the strcvt variable outside the loop. change your code to:

 public static int converter(int num) { int answer; int cvt = 0; String strcvt = null ; while (num >= 0) { int i = num / 3; int j = num % 3; String strj = Integer.toString(j); strcvt = Integer.toString(cvt); strcvt = strj + strcvt; num = i; break; } answer = Integer.parseInt(strcvt); return answer; } 
+1
source share

All Articles