settingsAccountsettings
Menusettings

Q: Convert from decimal system to base-7 - Java Task

+5 votes

Write a program that takes an integer number and converts it to base-7:

convert to base 7 in java

Write a program that converts from a base-7 number to its decimal representation:

convert from base-7 to decimal system - integer in java

asked in Java category by user hues
edited by user golearnweb

1 Answer

+2 votes
 
Best answer

Here is the solution for the first part: Write a program that takes an integer number and converts it to base-7:

import java.util.ArrayList;
import java.util.Scanner;

public class Pr_04_ConvertFromDecimalSystemToBase7 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number = scanner.nextInt();
        ArrayList<Integer> result = new ArrayList<>();

        int remainder = 0;
        boolean finish = false;

        while (!finish) {
            if (number == 0) {
                finish = true;
            } else {
                remainder = number % 7;
                number = number / 7;
                result.add(remainder);
            }
            remainder = 0;
        }
        for (int i = result.size()-1; i >=0 ; i--) {
            int a = result.get(i);
            System.out.print(a);
        }
        System.out.println();
    }
}

...and for the second part: Convert from base-7 to decimal:

import java.util.Locale;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner console = new Scanner(System.in);
        int result = 0;

        char[] chars = console.nextLine().toCharArray();

        int[] reverse = new int[chars.length];

        for (int i = chars.length - 1, j = 0; i >= 0; i--, j++) {

            reverse[j] = Integer.parseInt(String.valueOf(chars[i]));
        }

        for (int i = 0; i < reverse.length; i++) {

            int sum = (int) (reverse[i] * Math.pow(7, i));

            result += sum;
        }
        System.out.println(result);
    }
}
answered by user john7
selected by user golearnweb
...