I have a program whose intention is to take in a decimal integer and return the binary value.
public static int returnBinary(int number) {
int current;
int digit = 1;
int result = 0;
while (number > 0) {
current = number % 2;
number = number/2;
result = result + current * digit;
digit = digit * 10;
}
return result;
}
This program works perfectly until it reaches the value 1024, for which it returns the value: 1410065408
Larger values than 1024 also do not work. I noticed 1023 in binary is 1111111111, which may be relevant as to why 1024 does not work.
You are trying to assign a value which is higher than the Integer.MAX_VALUE. In Java it is 2.147.483.647 and the binary value of 1.111.111.111 might be 1023 in decimal, but it is around half of the Integer.MAX_VALUE. Anything higher is not representable in Integer. You might want to return a String instead.
You can return String rather than the integer, please find the string implementation below.
public static String returnBinary(int number) {
String result = "";
int digit;
while (number > 0) {
digit = number & 0X1;
result = digit+result;
number = number >> 1;
}
return result;
}
In binary 1024 is 10000000000 however max value for an int is 2 147 483 647 so you have exceeded the maximum size
Related
I wrote a program which, at first, was giving correct answers however I later wrote another method which caused my program to start failing. After that I deleted the second method but nothing seems to work to fix it. Can you guys tell me what the problem is?
Note: Method isNumeric just checks if the input String contains a non-numeric character.
For example: a number in octal basis "115" needs to be converted to decimal, meaning
(115)8 -> (?)10
The following formula gives us this:
115 = (1 × 8²) + (1 × 8¹) + (5 × 8⁰) = 77
This is the formula that the code is supposed to follow.
Therefore the result of the conversion of 115 in octal basis to decimal is 77.
Another limitation of this is that this must use recursion.
It worked in the sense that it gave the correct result 5 times in a row for different String number inputs but something along the way changed and now gives wrong results.
public static int octalStringToDecimal(String numString) {
//Base case the numeric value is just 0 or where String is empty
if ((numString.equals(""))) {
return -9999;
}
//the String does not contain numeric characters
if((!isNumeric(numString))){
return -9999;
}
int rem, sum = 0, i = 0, basis = 8;
int number = Integer.parseInt(numString); //this is n
//while our number is not 0 then we keep on parsing
while (number != 0) {
rem = number % 10;
number = number / 10;
sum = rem * ((int) Math.pow(basis, i)) + octalStringToDecimal(String.valueOf(number));
i++;
}
//when out number is equal to 0 then we return the value
return sum;
}
public static boolean isNumeric(String string) {
try {
Integer.parseInt(string);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Your "recursive" method contains a while loop. Recursive methods do not usually contain loops. A recursive method must contain a condition that terminates the recursion. If that condition is not true, then the method changes the arguments it was called with and then calls itself.
Since the parameter to your recursive method is a string, it seemed logical to me to extract the digits of the number using method substring(int, int).
Since the input number is supposed to be an octal number, apart from checking whether it contains only digits, you also need to check whether it is a valid octal number. In other words each digit in the number must be between 0 (zero) and 7 (seven).
In the below code, I initially take the rightmost digit of the input number and multiply it by 80. Then, in every recursive call, I take the digit immediately to the left of the last digit I converted and increase the exponent by one. Hence, the first recursive call will take the digit to the left of the rightmost digit and multiply it by 81.
Once I have converted the leftmost digit, the recursion stops.
public class Converter {
private static final int BASE = 8;
private static void checkDigit(String digit) {
int numeral = Integer.parseInt(digit);
if (numeral > 7) {
throw new IllegalArgumentException("Not a valid octal digit: " + digit);
}
}
private static int convertDigit(String digit, int exponent) {
return (int) Math.pow(BASE, exponent) * Integer.parseInt(digit);
}
private static int octalStringToDecimal(String numString, int exponent, int start) {
if (start >= 0) {
String digit = numString.substring(start, start + 1);
checkDigit(digit);
return convertDigit(digit, exponent) + octalStringToDecimal(numString, exponent + 1, start - 1);
}
else {
return 0;
}
}
public static void main(String[] args) {
String numString = "115";
System.out.println(octalStringToDecimal(numString, 0, numString.length() - 1));
}
}
I'm a novice Java coder working on a problem dealing with counting consecutive integers in the binary forms of numbers.
The numbers are read from the input, and converted to binary using the method called conversion. The binary form is then sent to a character array where the for loop checks for consecutive characters(specifically the number 1) and prints the maximum count as the final answer.
I've managed to get the code to a state where I feel it should be working, but I've only had success with about half of the test cases. The larger number conversions like 262,141 tend to produce incorrect answers. Can anyone tell me where I've gone wrong?
I have a suspicion that it's something to do with the character array, but after several hours of research I haven't been able to find a solution to my particular problem.
import java.io.*;
import java.util.*;
public class Solution {
public static int conversion(int decimal){//this will take the decimal from the input and convert it to binary
int result = 0;//the result from each step of the conversion
int base = 1;//used to multiply the remainder by 1, 10, 100 etc
while(decimal > 0){
int remainder = decimal % 2;//takes the remainder of the iteration
decimal = decimal / 2;//halves the decimal number
result = result + (remainder * base);//pseudo concatenation of the binary
base = base * 10;//increases the base multiplier to continue filling out the binary leftward
}
return result;//returns result after loop has finished
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();//scan the input to obtain the decimal number
int binaryForm = conversion(n);//convert the decimal to binary and assign to binaryForm variable
String stringForm = Integer.toString(binaryForm);//convert binaryForm to a String
int counter = 1;
int max = 1;
char testArray[] = stringForm.toCharArray();//send stringForm to fill out testArray
for(int i = 0; i < testArray.length - 1; i++){//loops through testArray to test stringForm values
if(testArray[i] == testArray[i + 1] && testArray[i] == '1'){//if consecutive values equal char 1, increase counter
counter += 1;
if(counter > max){
max = counter;//if counter is higher than current maxCounter, increase maxCounter
}
}
else {//if consecutive values do not equal 1, reset counter
counter = 1;
}
}
System.out.print(max);//print the maximum consecutive values for the decimal input when converted to binary
}
}
You are trying to create a binary representation of a decimal number using an integer. This will work for smaller numbers but it doesn't take long for you to reach an overflow. You should use a string representation of the binary number like so
String numBin = "";
while(num > 0)
{
numBin = num % 2 + numBin;
num = num / 2;
}
System.out.println("Binary Representation: " + numBin);
Then take that string and loop through it calculating the consecutive counts of 1's
int consecutiveCount = 0;
for(int i = 0; i < numBin.length() - 1; i++)
{
if(numBin.charAt(i) == '1' && numBin.charAt(i + 1) == '1')
{
consecutiveCount++;
}
}
System.out.println("Consecutive Count: " + consecutiveCount);
Output
Number: 261141
Binary Representation: 111111110000010101
Consecutive Count: 7
Number: 3
Binary Representation: 11
Consecutive Count: 1
Number: 18
Binary Representation: 10010
Consecutive Count: 0
Number: 1111111
Binary Representation: 100001111010001000111
Consecutive Count: 5
This is my function in Java:
public static String convertFromDecimal(int number, int base)
{
String result = "";
/*
* This while loop will keep running until 'number' is not 0
*/
while(number != 0)
{
result = (number%base) + result; // Appending the remainder
number = number / base; // Dividing the number by the base so we can get the next remainder
}
// If the number is already 0, then the while loop will ignore it, so we will return "0"
if(result == "")
{
return "0";
}
return result;
}
It works fine for numbers that convert to numbers not beginning with 0, if the number is supposed to have a zero at the start, it will not record it, could anyone tell me why?
For example, if I print out
convertFromDecimal(13,2) it returns
1101
Which is correct, but if I print out
convertFromDecimal(461,2), I get
111001101
Where the actual answer is
0000000111001101
So it's the same as my answer without the leading zeroes, if anyone knows why I would appreciate the help, thank you.
EDIT My question is different because I don't want 16 digits, I want the binary number of the given decimal, a calculator like this can explain what I want.
I assume you are looking to format all your answers as shorts (16 bits).
In this case, simply check the length of your current string, and add on zeroes as needed.
int zeroesRemaining = 16 - result.length();
for (int i = 0; i < zeroesRemaining; i++) {
result = "0" + result;
}
Alternatively, if you want to do it faster, use a StringBuilder.
int zeroesRemaining = 16 - result.length();
StringBuilder tempBuilder = new StringBuilder(result);
for (int i = 0; i < zeroesRemaining; i++) {
tempBuilder.insert(0, 0); //inserts the integer 0 at position 0 of the stringbuilder
}
return tempBuilder.toString(); //converts to string format
There is also probably a formatter that could do this, but I don't know of such.
If you want to change the number of zeroes to be the closest integer primitive, just set zeroesRemaining to be the (least power of 2 that is greater than the number of bits) minus (the number of bits).
Since you want fixed lengths for your result, in groups of 8 bits, the easiest way is to append 0 to the front of your result until its length is a multiple of 8.
That is as simple as
wile (result.length() % 8 > 0)
{
result = "0" + result;
}
return result;
How can i implement an algorithm to convert float or int to string?
I found one link
http://geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-0-2-years-about-algorithms-13
but i cant understand the algorithm given there
the numbers 0-9 are sequential in most character encoding so twiddling with the integral value of it will help here:
int val;
String str="";
while(val>0){
str = ('0'+(val%10)) + str;
val /= 10;
}
Here's a sample of how to do the integer to string, from it I hope you'll be able to figure out how to do the float to string.
public String intToString(int value) {
StringBuffer buffer = new StringBuffer();
if (value < 0) {
buffer.append("-");
}
// MAX_INT is just over 2 billion, so start by finding the number of billions.
int divisor = 1000000000;
while (divisor > 0) {
int digit = value / divisor; // integer division, so no remainder.
if (digit > 0) {
buffer.append('0'+digit);
value = value - digit * divisor; // subtract off the value to zero out that digit.
}
divisor = divisor / 10; // the next loop iteration should be in the 10's place to the right
}
}
This is of course, very unoptimized, but it gives you a feel for how the most basic formatting is accomplished.
Note that the technique of "" + x is actually rewritten to be something like
StringBuffer buffer = new StringBuffer();
buffer.append("");
buffer.append(String.valueOf(x));
buffer.toString();
So don't think that what is written is 100% exactly HOW it is done, look at is as what must happen in a larger view of things.
The general idea is to pick off the least significant digit by taking the number remainder ten. Then divide the number by 10 and repeat ... until you are left with zero.
Of course, it is a bit more complicated than that, especially in the float case.
if i have a single digit in int fomrat then i need to insert it into char , how to convert int to char?
Easy:
int digit = ... /* 0 to 9 */
char ch = (char)('0' + digit);
Well, you can read the code yourself.
I'm trying to take an integer as a parameter and then use recursion to double each digit in the integer.
For example doubleDigit(3487) would return 33448877.
I'm stuck because I can't figure out how I would read each number in the digit I guess.
To do this using recursion, use the modulus operator (%), dividing by 10 each time and accumulating your resulting string backwards, until you reach the base case (0), where there's nothing left to divide by. In the base case, you just return an empty string.
String doubleDigit(Integer digit) {
if (digit == 0) {
return "";
} else {
Integer thisDigit = digit % 10;
Integer remainingDigits = (digit - thisDigit) / 10;
return doubleDigit(remainingDigits) + thisDigit.toString() + thisDigit.toString();
}
}
If you're looking for a solution which returns an long instead of a String, you can use the following solution below (very similar to Chris', with the assumption of 0 as the base case):
long doubleDigit(long amt) {
if (amt == 0) return 0;
return doubleDigit(amt / 10) * 100 + (amt % 10) * 10 + amt % 10;
}
The function is of course limited by the maximum size of a long in Java.
I did the same question when doing Building Java Programs. Here is my solution which works for negative and positive numbers (and returns 0 for 0).
public static int doubleDigits(int n) {
if (n == 0) {
return 0;
} else {
int lastDigit = n % 10;
return 100 * doubleDigits(n / 10) + 10 * lastDigit + lastDigit;
}
There's no need to use recursion here.
I'm no longer a java guy, but an approximation of the algorithm I might use is this (works in C#, should translate directly to java):
int number = 3487;
int output = 0;
int shift = 1;
while (number > 0) {
int digit = number % 10; // get the least-significant digit
output += ((digit*10) + digit) * shift; // double it, shift it, add it to output
number /= 10; // move to the next digit
shift *= 100; // increase the amount we shift by two digits
}
This solution should work, but now that I've gone to the trouble of writing it, I realise that it is probably clearer to just convert the number to a string and manipulate that. Of course, that will be slower, but you almost certainly don't care about such a small speed difference :)
Edit:
Ok, so you have to use recursion. You already accepted a perfectly fine answer, but here's mine :)
private static long DoubleDigit(long input) {
if (input == 0) return 0; // don't recurse forever!
long digit = input % 10; // extract right-most digit
long doubled = (digit * 10) + digit; // "double" it
long remaining = input / 10; // extract the other digits
return doubled + 100*DoubleDigit(remaining); // recurse to get the result
}
Note I switched to long so it works with a few more digits.
You could get the String.valueOf(doubleDigit) representation of the given integer, then work with Commons StringUtils (easiest, in my opinion) to manipulate the String.
If you need to return another numeric value at that point (as opposed to the newly created/manipulated string) you can just do Integer.valueOf(yourString) or something like that.