Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a base 10 number to a base 3 number

Tags:

java

How to convert a base 10 number to a base 3 number with a method int converter(int num).

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();
}

It was Compilation completed. But when I tried to run it, and entered a number, it showed that java.lang.NumberFormatException: For input string: "strcvt" I don't know how to fix it. How can I do this without using string?

like image 512
AliceBobCatherineDough Avatar asked Feb 06 '15 08:02

AliceBobCatherineDough


People also ask

How do you convert a base 10 number to base 3?

The base 3, or ternary, system, uses only the digits 0,1, and 2. For each place, instead of multiplying by the power of 10, you multiply by the power of 3. For example, 120123→1×34+2×33+0×32+1×31+2.

How do you change a number to base 3?

Steps to Convert Decimal to Ternary:Divide the number by 3. Get the integer quotient for the next iteration. Get the remainder for the ternary digit. Repeat the steps until the quotient is equal to 0.

How do you convert a base 10 number to a base?

To convert any number in (our base) Base 10 to any other base, we must use basic division with remainders. Do not divide using decimals; the algorithm will not work. Keep dividing by 5, until your quotient is zero. Now write your remainders backwards!


2 Answers

"base 3 number" and "base 10 number" are the same number. In method int converter(int num) you're changing the number although you only need to change representation. Look at parseInt(String s, int radix) and toString(int i, int radix), that should help you.

like image 80
Sergey Fedorov Avatar answered Sep 23 '22 01:09

Sergey Fedorov


You have to parse the value of strcvt not the string "strcvt"

So you have to remove the double qoutes answer = Integer.parseInt(strcvt); And define the variable strcvt outside the loop. change you 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;
}
like image 21
Jens Avatar answered Sep 22 '22 01:09

Jens