Decimal to Binary in java - what is wrong with my code? - java

System.out.print("Enter an integer: ");
int number = input.nextInt();
String binary = "";
while(number != 0) {
if (number % 2 == 0) {
binary += "0" ;
} else{
binary += "1" ;
}
number /= 2;
}
System.out.println(binary);
I have trouble understanding what is wrong with my code.
I saw there are solutions to this question but they didn't answer the following question that I have :
I know that to display the binary the right way I need to change these line: binary += "0"; to this line: binary = "0" + binary;
I just can't understand WHY, why when I wrote that code the output is not reversed as it should be but If I add the lines it prints the right way.
Thanks.

Your code keeps checking the modulo of 2, which is in fact the least significant bit of the number, then it divides by two to move on to the next bit (move one bit to the right). For example:
29 = 11101
^ check modulo of two,
append "1",
divide by two
14 = 1110
^ check modulo of two,
append "0",
divide by two
7 = 111
^ check modulo of two,
append "1",
divide by two
3 = 11
^ check modulo of two,
append "1",
divide by two
1 = 1
^ check modulo of two,
append "1",
divide by two
(stop)
As you can see, the algorithm appends, in order:
1
0
1
1
1
Which is in fact the reverse of the binary representation. So, in other words, you need to add these digits at the beginning of the String:
while(number != 0) {
if (number % 2 == 0) {
binary = "0" + binary;
} else {
binary = "1" + binary;
}
number /= 2;
}

You are appending the binary digits in reversed order.
The first digit that you append to the String becomes the first character of the String, which means the least significant bit becomes the most significant bit in the output String.
It should be:
String binary = "";
while (number != 0) {
if (number % 2 == 0) {
binary = "0" + binary; // the newly appended digit should be to the left of the
// previously appended digits
} else {
binary = "1" + binary;
}
number /= 2;
}
System.out.println(binary);
Take a simple example:
Let number == 2
First iteration:
number % 2 == 0
binary = "0" + binary; // "0" + "" -> "0"
number /= 2; // now number == 1
Second iteration:
number % 2 != 0
binary = "1" + binary; // "1" + "0" -> "10"
number /= 2; // now number == 0

String binary = "";
while (number != 0) {
if (number % 2 == 0) {
binary = "0" + binary;
} else {
binary = "1" + binary;
}
number /= 2;
}
System.out.println(binary);
You can add at the front of the binary String.
There is an another way to do so by using the reverse() method.
String binary = "";
while (number != 0) {
if (number % 2 == 0) {
binary += "0" ;
} else {
binary += "1" ;
}
number /= 2;
}
String reverseBinary = new StringBuffer(binary).reverse().toString();
System.out.println(reverseBinary);

Related

The loop has no output?

The code below has no output when I run it, I think somehow it is infinite loop? How to fix it?
Write a method named getEvenDigitSum with one parameter of type int called number.
The method should return the sum of the even digits within the number.
If the number is negative, the method should return -1 to indicate an invalid value.
EXAMPLE INPUT/OUTPUT:
getEvenDigitSum(123456789); → should return 20 since 2 + 4 + 6 + 8 = 20
getEvenDigitSum(252); → should return 4 since 2 + 2 = 4
getEvenDigitSum(-22); → should return -1 since the number is negative
public class getEvenDigitSum {
public static int getEvenDigitSum(int number) {
int sum = 0;
int lastDigit=0;
if (number < 0) {
return -1;
}
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
}
return sum;
}
}
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
}
OK, and what happens if the number isn't even? You didn't make an else/else if statement after; if your number is odd, it stays the same, the loop is infinite, and hence your code does nothing.
Your condition only handles even digits, but think about what happens when you get a number that contains odd digit, like 1221 for example.
Try adding the missing else statement:
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
else {
// Deal with odd digit, leaving for you to implement
{
}
General tip: The best way to find errors in your code is to write tests and debug your code.
These are two skills every developer should poses and practice regularly

print two digit numbers which are less than or equal to 56 and the sum of digits is greater than 10 JAVA

why the following method doesn't work for printing two digit numbers which are less than or equal to 56 and the sum of digits is greater than 10 in JAVA
for (int i = 10; i <= 99; i++) {
String str = Integer.toString(i);
int sum = (str.charAt(0) + str.charAt(1));
if (sum > 10 && sum<=56) {
System.out.println("The first operation " + sum);
}
}
The third line: int sum = (str.charAt(0) + str.charAt(1)); is one of the problems. When i is 10, str.charAt(0) evaluates the the character 1 which has ascii value 49 and str.charAt(1) evaluates to the character 0 which has ascii value 48 producing a sum of 97 instead of the desired 1.
Instead you could use the modulus operator to strip-off the digits as needed. For example: int sum = ( i / 10 ) + (i % 10);.
*also, the range of i in your for loop should be adjusted as other users have commented.
Since you know any number greater than 56 won't pass your criteria, you need to change your loop to go from 10 to 56. Thus, you can exclude the second part of the if statement. Change the for loop to:
for (int i = 10; i <= 56; i++) {
and your if statement to:
if (sum > 10) {

How to list even and odd digits from integer inputs

Okay so my question is how can I display odd and even digits of a single int input not the whole input. This while using "for" or "while" loop and the % modulator. For example, the program ask a user to enter a positive integer and then it would read each digit and list even and odd digits. I was unable to find a method that reads each character except for the .charAt() but I cant make it work. This is my fail attempt. NOTE: I can't use the % modulator because idk any method to read each digit for an int. Please help, thanks.
String = userEntry
int r = userEntry.length() - 1;
System.out.print("The even numbers are ");
int c = 0; // 0 would count as even.
int size = 0;
while (size < r && c < 9)
{
if (c == userEntry.charAt(size))
{
outputFile.print(" " + userEntry.charAt(size));
System.out.print(" " + userEntry.charAt(size));
size++;
}
else
{
c+=2;
}
For that you can use the modulo operator.
public class Main {
/** http://stackoverflow.com/q/36053971/6077352 */
public static void main(String[] args) {
int input = 123456789;
while (input > 0) {
if (input % 2 == 0) {
System.out.println(input % 10 + " is even");
} else {
System.out.println(input % 10 + " is odd");
}
input = input / 10;
}
}
}
Example output:
9 is odd
8 is even
7 is odd
6 is even
5 is odd
4 is even
3 is odd
2 is even
1 is odd
An if statement would do the job of deciding whether the number is odd or even. As for the for statement, in order to run it through the whole array you would use code like this:
for(*variable* = 0; *variable* < userEntry.length; *variable*++)
{
}
The mod operator gives you the remainder of doing division on an int.
So any number mod 10 will return the last digit because the remainder of dividing a digit less than 10 is the number itself. So 30%10=0 and 32%10=2. So you can use the mod to separate the digits.
And then for each digit you want to check if if it is even or odd. even numbers are divisible by 2 so number%2 should leave no remainder.
You then have to divide your number by 10 to do the same for the tens column and then again for the hundreds column and so on. This should work for you.
while (number>0) {
if ((number%10)%2==0) {
System.out.println(number % 10 + "even");
}
else {
System.out.println(number % 10+ "odd");
}
number = number / 10;
}

How Can I Convert Very Large Decimal Numbers to Binary In Java

For instance, How would I be able to convert 2^60 or 12345678901234567890123456789012345678901234567890 to binary?
Basically, numbers that are too large to represent in Java.
Edit: I will be making a class that will be able to represent number that are too large. I'm just having a hard time figuring our how to convert decimal to binary.
Edit2: And also, I am not allowed to use BigDecimal, BigInteger, or any other library, sorry for not specifying earlier.
Here is a quik&dirty (very very very dirty) code:
public class BigDec2Bin {
public static int[] string2arrayReversed( String s )
{
char a[] = s.toCharArray();
int b[] = new int[ s.length() ];
for( int i = 0; i < a.length; i++ )
{
b[a.length-1-i] = a[i] - 48;
}
return b;
}
// adds two binary numbers represented as strings
public static String add( String s1, String s2 )
{
String result = "", stmp;
int[] a1, a2;
int ctmp, mark = 0;
// a1 should be the longer one
a1 = string2arrayReversed( ( s1.length() > s2.length() ? s1 : s2 ) );
a2 = string2arrayReversed( ( s1.length() < s2.length() ? s1 : s2 ) );
for( int i = 0; i < a1.length; i++ )
{
ctmp = a1[i] + ( i < a2.length ? a2[i] : 0 ) + mark;
switch( ctmp )
{
default:
case 0:
stmp = "0";
mark = 0;
break;
case 1:
stmp = "1";
mark = 0;
break;
case 2:
stmp = "0";
mark = 1;
break;
case 3:
stmp = "1";
mark = 1;
break;
}
result = stmp + result;
}
if( mark > 0 ) { result = "1" + result; }
return result;
}
public static String dec2bin( String s )
{
String result = "";
for( int i = 0; i < s.length() ; i++ )
{
result = add( result + "0", result + "000" );
result = add( result, Integer.toBinaryString( s.charAt(i) - 48 ) );
}
return result;
}
public static void main( String[] args )
{
String dec = "12345"; // should be 11000000111001
System.out.println( "dec2bin( " + dec + " ) = " + dec2bin( dec ) );
dec = "12345678901234567890123456789012345678901234567890";
System.out.println( "dec2bin( " + dec + " ) = " + dec2bin( dec ) );
}
}
Output:
dec2bin( 12345 ) = 011000000111001
dec2bin(
12345678901234567890123456789012345678901234567890
) =
10000111001001111111011000110110100110101010111110000011110010100001010100000010011001110100011110101111100011000111111100011001011011001110001111110000101011010010
My main idea is to use always strings.
add -method adds two binary numbers which are represented as strings
dec2bin -method is where the magic happens.
Allow me to explain:
result = add( result + "0", result + "000" );
is a calculation to multiply any given number by 10.
Multiplying a binary number by 10 is the same as adding the number with shifts:
x*10 <=> x<<1 + x<<3
result = add( result, Integer.toBinaryString( s.charAt(i) - 48 ) );
just adds a the next digit (from left to right) on the result string
Basicly what I'm doing is for example with 1234:
0*10 + 1 = 1
1*10 + 2 = 12
12*10 + 3 = 123
123*10 + 4 = 1234
but only in binary (represented as strings).
I hope i could help and sorry for my bad english.
Try this:
new BigDecimal("12345678901234567890123456789012345678901234567890").toString(2);
Edit:
For making a big-number class, you may want to have a look at my post about this a week ago. Ah, the question was by you, never mind.
The conversion between different number systems in principle is a repeated "division, remainder, multiply, add" operation. Let's look at an example:
We want to convert 123 from decimal to a base 3 number. What do we do?
Take the remainder modulo 3 - prepend this digit to the result.
Divide by 3.
If the number is bigger than 0, continue with this number at step 1
So it looks like this:
123 % 3 == 0. ==> The last digit is 0.
123 / 3 == 41.
41 % 3 == 2 ==> The second last digit is 2.
41 / 3 == 13
13 % 3 == 1 ==> The third digit is 1.
13 / 3 == 4
4 % 3 == 1 ==> The fourth digit is 1 again.
4 / 3 == 1
1 % 3 == 1 ==> The fifth digit is 1.
So, we have 11120 as the result.
The problem is that for this you need to have already some kind of division by 3 in decimal format, which is usually not the case if you don't implement your number in a decimal-based format (like I did in the answer to your last question linked above).
But it works for converting from your internal number format to any external format.
So, let's look at how we would do the inverse calculation, from 11120 (base 3) to its decimal equivalent. (Base 3 is here the placeholder for an arbitrary radix, Base 10 the placeholder for your internal radix.) In principle, this number can be written as this:
1 * 3^4 + 1 * 3^3 + 1*3^2 + 2*3^1 + 0*3^0
A better way (faster to calculate) is this:
((((1 * 3) + 1 )*3 + 1 )*3 + 2)*3 + 0
1
3
4
12
13
39
41
123
123
(This is known as Horner scheme, normally used for calculating values of polynomials.)
You can implement this in the number scheme you are implementing, if you know how to represent the input radix (and the digits) in your target system.
(I just added such a calculation to my DecimalBigInt class, but you may want to do the calculations directly in your internal data structure instead of creating a new object (or even two) of your BigNumber class for every decimal digit to be input.)
What about this approach:
result = 0;
for each digit in the decimal number, from left to right
result = result * 10 + digit;
return result;
So we need a way to represent an arbitrarily large binary number, and implement multiplication by 10 and addition of small numbers.
The most straightforward way to represent an arbitrarily large binary number is an array of its binary digits. You can then apply the algorithms for addition and multiplication your learned in elementary school, except that digits will "overflow" when they exceed 1 rather than 9. For example:
1010 * 1100111
----------------
11001110
+ 1100111000
----------------
10000000110
Pew: thanks, that works for some numbers. The number 6123456789012 however doesn't work, but here is the fix:
// a1 should be the longer one
a1 = string2arrayReversed( ( s1.length() >= s2.length() ? s1 : s2 ) ); //GREATER EQUAL
If you only work with integers, use BigInteger.toByteArray.
If not, unfortunately BigDecimal doesn't have that method. But I suppose you can always (in both cases) just ASCII encode the string representation of the number, if the binary form is just meant for transfer and not calculation anywhere.
there is a fast program to get the binary representation of a huge decimal.
This programm is indeed fast, it takes only 20ms to deal with a decimal with 3000digits, eg:string(3000,'2')+'12345'. because of the pursuit of efficiency, it is not very readable. you can modify it yourself to make it easier to understand.
inline string remove_pre_zero(const string& a)
{
auto t = a.find_first_not_of('\0', 0);
if (t == a.npos)
return string("0");
else
return a.substr(t);
}
string convert_to_bin(const string& _s)
{
const static string str[] = { "0", "1" };
string s(_s.size(), '0');
string binary;
binary.reserve(_s.size()*3);
int i = 0;
for (const auto& c : _s)
s[i++] = (c - '0');
while (s!="0")//simulate divide by 2
{
int t = 0, old_t = 0;
for (auto& ch : s)
{
t = ((old_t * 10 + ch) & 1);
ch = (ch + old_t * 10) >>1;
old_t = t;
}
binary += str[t];
if (s[0] == 0)
s = remove_pre_zero(s);
}
return string(binary.rbegin(), binary.rend());
}

checking an integer to see if it contains a zero

Given an integer, how could you check if it contains a 0, using Java?
1 = Good
2 = Good
...
9 = Good
10 = BAD!
101 = BAD!
1026 = BAD!
1111 = Good
How can this be done?
Do you mean if the decimal representation contains a 0? The absolute simplest way of doing that is:
if (String.valueOf(x).contains("0"))
Don't forget that a number doesn't "inherently" contain a 0 or not (except for zero itself, of course) - it depends on the base. So "10" in decimal is "A" in hex, and "10" in hex is "16" in decimal... in both cases the result would change.
There may be more efficient ways of testing for the presence of a zero in the decimal representation of an integer, but they're likely to be considerably more involved that the expression above.
If for some reason you don't like the solution that converts to a String you can try:
boolean containsZero(int num) {
if(num == 0)
return true;
if(num < 0)
num = -num;
while(num > 0) {
if(num % 10 == 0)
return true;
num /= 10;
}
return false;
}
This is also assuming num is base 10.
Edit: added conditions to deal with negative numbers and 0 itself.
You can convert it to a string and check if it contains the char "0".
int number = 101;
if( ( "" + number ).contains( "0" ) ) {
System.out.println( "contains the digit 0" );
}
Integer.toString(yourIntValue).contains("0");
Here is a routine that will work detect zeros in integers. To make it work with any representation (decimal, hex, octal, binary), you need to pass in the base as a parameter.
public static boolean hasZero(int num, int base) {
assert base > 0 : "must have positive non-zero base";
if (num == 0)
return true;
while(num != 0) {
if (num % base == 0) {
return true;
}
else {
num = num / base;
}
}
return false;
}
public static void main(String args[]) {
System.out.println(hasZero(10, 10)); // true (base 10 int)
System.out.println(hasZero(-12, 10)); // false (base 10 int)
System.out.println(hasZero(0x10, 16)); // true (hex is base 16)
System.out.println(hasZero(0x1A, 16)); // false (hex is base 16)
}
I don't know if this is easier but here is another way.
Split the number into an array of ints. Then sort and check if the first element is zero.
E.g
int n = 14501;
// after splitting
int na = {1, 4, 5, 0, 1};
// after sorting
int na = {0, 1, 1, 4, 5};
Not using Java, but it's not exactly hard to convert from C++
PS. Shame on anyone using string conversion.
bool Contains0InBase10( unsigned int i, unsigned int& next )
{
unsigned int divisor = 10;
unsigned int remainder = 0;
while( divisor <= i )
{
unsigned int newRemainder = i%divisor;
if( newRemainder - remainder == 0)
{
// give back information allowing a program to skip closer to the next
// number that doesn't contain 0
next = i + (divisor / 10) - remainder;
return true;
}
divisor *= 10;
remainder = newRemainder;
}
return false;
}

Categories

Resources