Results 1 to 3 of 3
- 10-04-2011, 05:45 AM #1
Member
- Join Date
- Sep 2011
- Posts
- 45
- Rep Power
- 0
Reads a number and prints it's binary digits, need help :)
Java Code:import java.util.Scanner; //Class definition public class Bits { public static void main(String[] args) { // declare int n; int rem; // User input Scanner in = new Scanner(System.in); System.out.println(); n = in.nextInt(); // Calculate while (n > 0) { System.out.print(rem = n % 2); n = n / 2; } } }
For example, if the input is 244, you should get 11110100, whereas I get 00101111. Keep in mind I didn't even know how binary worked before this problem so I wouldn't be surprised if my program isn't all that accurate to what I should have. Also, he says my result should be a string not an int. I don't really understand how that works...
Edit, I think my binary is correct. He wants the most significant bits on the left though.Last edited by Aimforthehead; 10-04-2011 at 05:59 AM.
- 10-04-2011, 07:31 PM #2
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 785
- Rep Power
- 12
Re: Reads a number and prints it's binary digits, need help :)
You have to use a StringBuilder with the method insert with the offset of 0 :)
After your loop you can print the builder.toString !
StringBuilder binary = new StringBuilder();
// Calculate
while (n > 0) {
binary.insert(0,rem = n % 2);
n = n / 2;
}
System.out.println(binary);
Or if you dont know the stringbuilder class, use the normal string class
binary = (rem = n % 2) + binary;
- 10-04-2011, 07:39 PM #3
Senior Member
- Join Date
- Nov 2010
- Posts
- 210
- Rep Power
- 11
Re: Reads a number and prints it's binary digits, need help :)
When working with bits, it's worth keeping the bitwise operators in mind. Your problem can be solved without them, but situations like these are exactly what they're there for.
To check whether a given bit is set, you can do something like the following:
Java Code:final int NUMBER_OF_BITS_INT = 32; private boolean isBitSet(int num, int bit) { /* bit must be between 1 and 32 */ return (num & 1 << (NUMBER_OF_BITS_INT - bit)) != 0; }
Last edited by Iron Lion; 10-04-2011 at 07:46 PM.
Similar Threads
-
need help with Number Pyramid with Double Digits
By SmellyFoot in forum New To JavaReplies: 5Last Post: 03-29-2011, 01:04 PM -
Separating the digits of given number
By lb2 in forum New To JavaReplies: 5Last Post: 09-09-2010, 06:29 AM -
All possible combinations given a binary number
By LeanA in forum New To JavaReplies: 9Last Post: 06-18-2010, 06:33 PM -
Count number of digits in string using scanner
By wendysbiggy in forum New To JavaReplies: 35Last Post: 01-20-2010, 06:11 AM -
Converts a binary number to a decimal
By cachi in forum New To JavaReplies: 1Last Post: 08-01-2007, 10:57 AM
Bookmarks