Denary number to hexadecimal - java

As a homework, I was asked to write a program which would convert a denary number to hexadecimal. What I've created kinda works but as the output it gives me reversed number and I have no idea how to solve it (it is my first program).
public static void main(String[] args) {
System.out.println("Give a denary number: ");
Scanner sc = new Scanner(System.in);
int dec1 = sc.nextInt();
String dec = Integer.toString(dec1);
int zmienna;
for(int i = 0; i < dec.length(); i++) {
zmienna = dec1 % 16;
dec1 = dec1 / 16;
if(zmienna == 10) {
System.out.print("A");
}
else if (zmienna == 11) {
System.out.print("B");
}
else if (zmienna == 12) {
System.out.print("C");
}
else if (zmienna == 13) {
System.out.print("D");
}
else if (zmienna == 14) {
System.out.print("E");
}
else if (zmienna == 15) {
System.out.print("F");
}
else if (zmienna == 0 & i == dec.length() - 1) {
System.out.print("");
}
else {
System.out.print(zmienna);
}
}
}

I just change a little in your program i just tried to solve your problem and it works. I just added a StringBuilder and append characters and at the last reverse it.
code
import java.util.Scanner;
public class A {
public static void main(String[] args) {
System.out.println("Give a denary number: ");
Scanner sc = new Scanner(System.in);
int dec1 = sc.nextInt();
StringBuilder sb =new StringBuilder();
String dec = Integer.toString(dec1);
int zmienna;
for(int i = 0; i < dec.length(); i++) {
zmienna = dec1 % 16;
dec1 = dec1 / 16;
if(zmienna == 10) {
//System.out.print("A");
sb.append("A");
}
else if (zmienna == 11) {
//System.out.print("B");
sb.append("B");
}
else if (zmienna == 12) {
//System.out.print("C");
sb.append("C");
}
else if (zmienna == 13) {
//System.out.print("D");
sb.append("D");
}
else if (zmienna == 14) {
//System.out.print("E");
sb.append("E");
}
else if (zmienna == 15) {
// System.out.print("F");
sb.append("F");
}
else if (zmienna == 0 & i == dec.length() - 1) {
System.out.print("");
}
else {
//System.out.print(zmienna);
sb.append(zmienna);
}
}
System.out.println(sb.reverse());
}
}

Related

Is there a solution to prevent this recursion?

In this program, a randomly generated 2D array is populated with 1's or 0's and I attempt to find a path of 1's (no diagonal movement). I have got the program to work for smaller dimensions of the 2D array, but when the dimensions are too large, the error Exception in thread "main" java.lang.StackOverflowError occurs.
import java.util.Scanner;
import java.util.Random;
public class Daft {
private int counter = 0;
public static void main(String[] args) {
Daft punk = new Daft();
punk.run();
}
public void run() {
int ans;
int[][] array;
int[][] solvedPath;
do {
counter = 1;
array = populate(defineArray(firstDimension(),secondDimension()));
solvedPath = findPath(array);
System.out.println("Times before solvable: " + counter);
print(solvedPath);
ans = continuity();
}while(ans != 0);
}
public int[][] findPath(int[][] array) {
int r = 0, c = 0;
while(true) {
array[0][0] = 7;
if(c == 0 && r == array.length-1) { //reached the bottom left, checks right
if(array[r][c+1] == 1) {
array[r][c+1] = 7;
c+=1;
} else {
array[r][c] = 7;
break;
}
} else if(c == array[0].length-1 && r == array.length-1) { //reached the bottom right, checks left
if(array[r][c-1] == 1) {
array[r][c-1] = 7;
} else {
array[r][c] = 7;
break;
}
} else if(r == array.length-1) { //reached the bottom, checks left/right
if(array[r][c+1] == 1 && array[r][c-1] == 1) {
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) { //checks right
array[r][c+1] = 7;
c+=1;
} else if(array[r][c-1] == 1) { //checks left
array[r][c-1] = 7;
c-=1;
} else { //end of path
array[r][c] = 7;
break;
}
} else if(c == 0) { //reached the left, checks right/bottom
if(array[r][c+1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) {
array[r][c+1] = 7;
c+=1;
} else if(array[r+1][c] == 1) {
array[r+1][c] = 7;
r+=1;
} else {
counter++; //path has ended, not solvable
newPath(array);
break;
}
} else if(c == array[0].length-1) { //reached the right, checks left/bottom
if(array[r+1][c] == 1 && array[r][c-1] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r+1][c] == 1) {
array[r+1][c] = 7;
r+=1;
} else if(array[r][c-1] == 1) {
array[r][c-1] = 7;
c-=1;
} else {
counter++; //path has ended, not solvable
newPath(array);
break;
}
} else if(array[r][c+1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c-1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) { //checks right
array[r][c+1] = 7;
c+=1;
} else if(array[r+1][c] == 1) { //checks bottom
array[r+1][c] = 7;
r+=1;
} else if(array[r][c-1] == 1) { //checks left
array[r][c-1] = 7;
c-=1;
} else {
counter++;
newPath(array);
break;
}
}
return array;
}
public int firstDimension() {
Scanner in = new Scanner(System.in);
System.out.println("Size of the first dimension:");
return in.nextInt();
}
public int secondDimension() {
Scanner in = new Scanner(System.in);
System.out.println("Size of the second dimension:");
return in.nextInt();
}
public int[][] defineArray(int firstDimension, int secondDimension) {
return new int[firstDimension][secondDimension];
}
public int[][] populate(int[][] array) {
Random rand = new Random();
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[i].length; j++) {
array[i][j] = rand.nextInt(2);
}
}
return array;
}
public int continuity() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number to continue (0 to quit):");
return in.nextInt();
}
public void print(int[][] array) {
for(int[] ints : array) {
for(int anInt : ints) {
System.out.print(anInt + " ");
}
System.out.println();
}
System.out.println();
}
public void newPath(int[][] array) {
findPath(populate(array));
}
}

Wheel of Fortune: building string

I am working on code for an assignment in which I have to make Wheel of Fortune, I am having trouble with building the string that will be shown to the user after each guess. I have the wheel spin working but I just can't seem to figure how to build the string. I can also answer any questions about this if you have any. Any help will be much appreciated. Here is my code so far:
class WheelOfFortune3 {
public static void main(String[] args) {
int result, location, newLocation, numGuess = 0;
String puzzle, guess;
String sub[] = new String[26];
for (int i = 0; i < sub.length; i++) {
sub[i] = "_";
}
result = wheelResult();
System.out.println("You spun $" + result);
puzzle = getPuzzle();
System.out.println(puzzle);
do {
guess = In.getString();
location = checkGuess(puzzle, guess);
if (location == -1) {
System.out.println("Incorrect guess");
}
if (location >= 0 && location <= 25) {
System.out.println("Correct guess");
newLocation = location + 1;
sub[numGuess] = puzzle.substring(location, newLocation);
for (int i = 0; i <= 10; i++) {
System.out.print(sub[i] + " ");
}
System.out.println("");
numGuess = numGuess + 1;
System.out.println(numGuess);
System.out.println(sub.length);
}
}
while (numGuess < sub.length);
}
public static int checkGuess(String puzzle, String guess) {
String word = puzzle;
int location;
location = word.indexOf(guess);
return location;
}
public static int wheelResult() {
int result;
int[] wheelSpin = new int[1];
wheelSpin[0] = (int)(24 * Math.random());
if (wheelSpin[0] == 1 || wheelSpin[0] == 18 || wheelSpin[0] == 22) {
result = 200;
return result;
} else if (wheelSpin[0] == 2 || wheelSpin[0] == 5) {
result = 900;
return result;
} else if (wheelSpin[0] == 0 || wheelSpin[0] == 3 || wheelSpin[0] == 15) {
result = 250;
return result;
} else if (wheelSpin[0] == 4 || wheelSpin[0] == 6 || wheelSpin[0] == 12 || wheelSpin[0] == 16) {
result = 300;
return result;
} else if (wheelSpin[0] == 7) {
result = 1500;
return result;
} else if (wheelSpin[0] == 9 || wheelSpin[0] == 11) {
result = 700;
return result;
} else if (wheelSpin[0] == 10 || wheelSpin[0] == 14 || wheelSpin[0] == 21) {
result = 500;
return result;
} else if (wheelSpin[0] == 13) {
result = 5000;
return result;
} else if (wheelSpin[0] == 23 || wheelSpin[0] == 19) {
result = 600;
return result;
} else if (wheelSpin[0] == 8 || wheelSpin[0] == 20) {
result = 100;
return result;
} else if (wheelSpin[0] == 17) {
result = 17;
return result;
}
return -1;
}
public static String getPuzzle() {
String puzzle;
//a long ride
return "A long ride";
//01234567890
}
}
This can be done using a List of Characters and the .contains() method like so:
List<Character> guessedCharacters = new ArrayList<>();
each time a player guesses a letter, add that letter to
the guessedCharacters List like this: guessedCharacters.add(char);
Then you can do something like this to generate the String to output to the player:
StringBuilder toShowSB = new StringBuilder();
for(int i=0,n=puzzle.length;i<n;i++){
if(guessedCharacters.contains(puzzle.charAt(i))){
toShowSB.append(puzzel.charAt(i));
}else{
toShowSB.append("_");
}
}
String toShow = toShowSB.toString();
This will create a String that holds all of the guessed letters in their places and an underscore denoting characters that have not been properly guessed yet.

Time limit exceeded online judge

This is the problem :
Input
The first line of input will contain the number of test cases, T (1 ≤ T ≤ 50). Each of the following T
lines contains a positive integer N that is no more than 80 digits in length.
Output
The output of each test case will be a single line containing the smallest palindrome that is greater
than or equal to the input number.
Sample Input
2
42
321
Sample Output
44
323
I keep having time limit exceeded when i submit to the code to online judge ( 3 seconds limit)
class Main {
static String ReadLn (int maxLg)
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
static boolean isPalandriome(String s){
String newString = "";
for(int i =s.length()-1;i >= 0; i--){
newString += s.charAt(i);
}
if(newString.equals(s))
return true;
else
return false;
}
public static void main(String[] args) {
BigInteger entredNumber;
String input;
input = Main.ReadLn(10);
int tests = Integer.parseInt(input);
List<BigInteger> numbers = new ArrayList<BigInteger>();
for (int i =0;i<tests;i++)
{
input = Main.ReadLn(100);
entredNumber = new BigInteger(input);
numbers.add(entredNumber);
}
for(int i=0;i<tests;i++){
BigInteger number = numbers.get(i);
while(!isPalandriome(String.valueOf(number))){
number = number.add(BigInteger.ONE);
}
System.out.println(number);
}
}
}
I can't find what takes too much time in my code.
At last coded Hope you find this helpful took 0.10 seconds
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
CustomReader cr = new CustomReader(1000000);
int T = cr.nextInt(), fIndex, bIndex, fStartIndex, bStartIndex;
StringBuilder output = new StringBuilder();
byte[] input;
boolean isAppend1 = false;
for (int i = 0; i < T; i++) {
input = cr.nextInput();
fStartIndex = bStartIndex = cr.getCurrInputLength() / 2;
isAppend1 = false;
if (cr.getCurrInputLength() % 2 == 0) {
bStartIndex--;
}
fIndex = fStartIndex;
bIndex = bStartIndex;
while (input[bIndex] == input[fIndex]) {
if (bIndex - 1 < 0) {
break;
} else {
bIndex--;
fIndex++;
}
}
if (input[bIndex] > input[fIndex]) {
while (bIndex >= 0) {
input[fIndex++] = input[bIndex--];
}
} else {
if (input[bStartIndex] < 57) {
input[bStartIndex] = (byte) (input[bStartIndex] + 1);
} else {
bIndex = bStartIndex;
while (bIndex >= 0 && input[bIndex] == 57) {
input[bIndex] = 48;
bIndex--;
}
if (bIndex >= 0) {
input[bIndex] = (byte) (input[bIndex] + 1);
} else {
input[0] = 49;
if (fStartIndex != bStartIndex) {
input[fStartIndex] = 48;
bStartIndex = fStartIndex;
} else {
input[fStartIndex + 1] = 48;
bStartIndex = fStartIndex = fStartIndex + 1;
}
isAppend1 = true;
}
}
while (bStartIndex > -1) {
input[fStartIndex++] = input[bStartIndex--];
}
}
for (int j = 0; j < cr.getCurrInputLength(); j++) {
output.append((char) input[j]);
}
if (isAppend1) {
output.append("1");
}
output.append("\n");
}
System.out.print(output.toString());
// genInput();
}
private static class CustomReader {
private byte[] buffer;
private byte[] currInput = new byte[1000000];
private int currInputLength;
private int currIndex;
private int validBytesInBuffer;
CustomReader(int buffSize) {
buffer = new byte[buffSize];
}
public int nextInt() throws IOException {
int value;
byte b;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
break;
}
}
value = b - 48;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
value = (value * 10) + (b - 48);
} else {
break;
}
}
return value;
}
public byte[] nextInput() throws IOException {
byte b;
this.currInputLength = 0;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
break;
}
}
currInput[currInputLength++] = b;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
currInput[currInputLength++] = b;
} else {
break;
}
}
return this.currInput;
}
public int getCurrInputLength() {
return this.currInputLength;
}
private byte getNextByte() throws IOException {
if (currIndex == buffer.length || currIndex == validBytesInBuffer) {
validBytesInBuffer = System.in.read(buffer);
currIndex = 0;
}
return buffer[currIndex++];
}
}
public static void genInput() {
for (int i = 0; i < 100; i++) {
System.out.println((int) (Math.random() * 1000000000));
}
}
}

how to find upside down of a 2digit number

I am trying to write program to find upside down of all double digit number. Actually I have written this code and it works pretty well too. Any other alternatives to find upside down of an integer. Say 18=81 and 96=69....
List < Integer > al = new ArrayList < Integer > ();
al.add(10);al.add(11);al.add(16);al.add(18);al.add(19);al.add(60);al.add(61);
al.add(66);al.add(69);al.add(80);al.add(81);al.add(86);al.add(88);al.add(91);
al.add(96);al.add(98);al.add(99);
Scanner s = new Scanner(System.in);
Integer n = s.nextInt();
if (((String)"" + n).length() == 2) {
if (al.contains(n))
System.out.println("yes");
else
System.out.println("no");
}
This is a simple, general algorithm analysing an integer w.r.t. digits with vertical symmetry. (It depends on a certain style of writing digits; note that "continental" '1' is not symmetrical.)
private static int[] other = new int[]{0, 1, -1, -1, -1, -1, 9, -1, 8, 6};
public static int invert( int n ){
int units = n % 10;
n /= 10;
int inv = other[units];
if( n == 0 ) return inv;
return inv < 0 ? -1 : invert( n )*10 + inv;
}
If a negative value is returned, the number is not symmetrical.
public static void main(String[] args) throws Exception {
for( int i = 100; i <= 199; ++i ){
int invi = invert( i );
if( invi > 0 ){
System.out.println( i + ": " + invi );
}
}
}
This is a better way of doing it.
It not only prints yes or no, but also the up side down number
public static void main(String[] args) {
List<String> al = new ArrayList<String>();
al.add("0");
al.add("1");
al.add("6");
al.add("8");
al.add("9");
Scanner s = new Scanner(System.in);
Integer n = s.nextInt();
String num = n + "";
if (num.length() == 2) {
if(al.contains(num.charAt(0) + "") && al.contains(num.charAt(1) + "")) {
System.out.println("Yes");
String upSideDownNumber = "";
if(num.charAt(1) == 6) {
upSideDownNumber += 9;
} else if(num.charAt(1) == 9) {
upSideDownNumber += 6;
} else {
upSideDownNumber += num.charAt(1);
}
if(num.charAt(0) == 6) {
upSideDownNumber += 9;
} else if(num.charAt(0) == 9) {
upSideDownNumber += 6;
} else {
upSideDownNumber += num.charAt(0);
}
System.out.println("The up side down number is " + upSideDownNumber);
} else {
System.out.println("No");
}
} else {
System.out.println("No");
}
}
Since only 0,1,6,8,9 look like digits when inverted. You can so below:
public static void main(String[] args) throws IOException {
Set<Integer> upsideDownProperDigits = new TreeSet<>(Arrays.asList(0,1,8,9,6));
Scanner s = new Scanner(System.in);
Integer n = s.nextInt();
boolean found = true;
while( n != 0){
int digit = n % 10;
if(!upsideDownProperDigits.contains(digit)){
found = false;
break;
}
n = n/10;
}
if(found){
System.out.println("yes");
}
else{
System.out.println("no");
}
}

Roman number to decimal in Java

I have to make a program that converts Roman numbers to decimal. I am confused about how to write the conditions for the Roman numbers, such as IV (4), IX (9), XL (40) and CM(900). The code that I wrote works for all the other numbers.
public static void main(String[] args) {
System.out.print("Enter a roman numeral: ");
Scanner in = new Scanner(System.in);
String Roman = in.next();
int largo = Roman.length();
char Roman2[] = new char[largo];
int Roman3[] = new int[largo];
for (int i = 0; i < largo; i++) {
Roman2[i] = Roman.charAt(i);
}
for (int i = 0; i < largo; i++) {
if (Roman2[i] == 'I') {
Roman3[i] = 1;
} else if (Roman2[i] == 'V') {
Roman3[i] = 5;
} else if (Roman2[i] == 'X') {
Roman3[i] = 10;
} else if (Roman2[i] == 'L') {
Roman3[i] = 50;
} else if (Roman2[i] == 'C') {
Roman3[i] = 100;
} else if (Roman2[i] == 'M') {
Roman3[i] = 1000;
}
}
int total = 0;
for (int m = 0; m < Roman3.length; m++) {
total += Roman3[m];
}
System.out.println("The Roman is equal to " + total);
}
You can check the previous digit.
For example, I added the condition that detects IV :
if (Roman2[i]=='I'){
Roman3[i]=1;
} else if (Roman2[i]=='V'){
Roman3[i]=5;
if (i>0 && Roman2[i-1]=='I') { // check for IV
Roman3[i]=4;
Roman3[i-1]=0;
}
} else if (Roman2[i]=='X'){
Roman3[i]=10;
} else if (Roman2[i]=='L'){
Roman3[i]=50;
} else if (Roman2[i]=='C'){
Roman3[i]=100;
} else if (Roman2[i]=='M'){
Roman3[i]=1000;
}
Define enum like below:
public enum RomanSymbol {
I(1), V(5), X(10), L(50), C(100), D(500), M(1000);
private final int value;
private RomanSymbol(final int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public int calculateIntEquivalent(final int lastArabicNumber, final int totalArabicResult) {
if (lastArabicNumber > this.value) {
return totalArabicResult - this.value;
} else {
return totalArabicResult + this.value;
}
}
}
And use it like RomanSymbol.I.getValue() which will return 1 and similarly for other.
So if you accept character from user, you can get the values as:
char symbol = 'I';//lets assume this is what user has entered.
RomanSymbol rSymbol = RomanSymbol.valueOf(String.valueOf(symbol));
int invalue = rSymbol.getValue();
And if you have string like IV, then you could calculate on something like for example:
int lastValue = rSymbol.calculateIntEquivalent(intValue, 0);
lastValue = rSymbol.calculateIntEquivalent(intValue, lastValue); //and so on

Categories

Resources