My goal is to get a String of ones and zeroes from input, then use the bin2Dec method to parse that binary string into a decimal number. How can I convert this correctly?
Here is what I have so far:
public class Tester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a binary number string: ");
String s = input.nextLine();
System.out.println("The decimal value is " + bin2Dec(s));
}
public static int bin2Dec(String binaryString){
}
}
The algorithm to do this is actually pretty simple.
If you look at a binary string, say, "10110" (22), what you'll notice is that equals 16 + 4 + 2. Look at this a bit harder, and you'll see it corresponds to 1 * 2^4 + 0 * 2^3 + 1 * 2^2 + 1 * 2^1 + 0 * 2^0. See the pattern? For each digit with value v and position n, it's "contribution" to the total sum is v * 2^n.
Now, this problem is actually easier to do iteratively (With a for-loop), but I assume this is a homework question and therefore you have to do it recursively.
You'll need to make another method, public static int bin2dec(String bin, int position) (this is called overloading the method, two methods can have the same name as long as their signatures are different). In this new method, you can follow the algorithm outlined above:
If position equals bin.length(), you've gone past the end of the string. Just return 0.
Otherwise, set v equal to the integer value of the character at position (You can either use the integer parse method, or just an if/ternary because there are only two options).
Multiply v by 2^position (hint: Math.pow).
Return v plus bin2dec(bin, position + 1) (this is the actual recursive part).
Now, in the original bin2dec, you can just put return bin2dec(bin, 0). That just allows you to call bin2dec without initializing the recursive counter, which is just general bookkeeping that callers don't want to deal with (not so important here, but very important in larger projects).
public static String showAsBinString(int n, String s){
if(n > 1){
s = showAsBinString(n/2, s);
}
s += n%2 == 0 ? "0" : "1";
return s;
}
System.out.println(showAsBinString(45, ""));
101101
Related
So for my project I have to write a method to convert double values to a string. I understand how to do this multiple ways multiple options of formatting. What I'm confused about is how would I turn half sizes(shoes) into a fraction version while still converting it to a string. So
10.5
returns
10 - 1/2
Any tips or helpful pointers are appreciated. Sorry if this is a dumb question I am still learning. :)
What you want can be done with the modulus operator (%) which in Java can be used with floating point values. If you do shoeSize % 1 you will get 0.5 with half sizes and 0.0 with others, so you only have to check that value to add the "1/2" to the string representation or not. Here is a simple example
public class ShoeSize {
double size;
public ShoeSize(double size) { this.size = size; }
public String toString() {
return "" + (int)size + (size % 1 == 0.5? " 1/2" : "");
}
public static void main(String args[]) {
ShoeSize ss1 = new ShoeSize(10.5);
ShoeSize ss2 = new ShoeSize(11);
ShoeSize ss3 = new ShoeSize(11.5);
System.out.println(ss1);
System.out.println(ss2);
System.out.println(ss3);
}
}
The result of the previous code is:
10 1/2
11
11 1/2
However, you really shouldn't go with that approach. That is because depending on the way you manage the shoe size values it can lead to unpredictable results, just because arithmetic in floating point values is not precise as it is with integer values. Some simple operations like the following can introduce enough error so the result is not what you expect:
...
public static void main(String args[]) {
ShoeSize ss = new ShoeSize(10.0);
ss.size += 0.1 + 0.2 + 0.3; // Sum it half
System.out.println(ss);
}
This code now prints 10 instead of 10 1/2.
What should you do instead? Well, there are several ways. You could for example store the shoe size inside ints representing, with each unit representing a half. This internal representation will be much error-prone if you have operations like addSize or subtracts. The only problem will be reading the size of the user; the best way is probably having a list of predefined sizes for the user to choose. Here is an example:
public class ShoeSize {
int halves;
public ShoeSize(double size) { this.halves = (int)(size * 2); }
public String toString() {
return "" + (halves / 2) + (halves % 2 == 1? " 1/2": "");
}
public static void main(String args[]) {
ShoeSize ss = new ShoeSize(10.5);
System.out.println(ss);
}
}
Still better, since the shoe sizes use to be very restricted between certain values, you could represent their values in a single enum. Every enum can be constructed from the human-readable string of the size (ex. "10 1/2") and there would never be problems with invalid shoe sizes. The only problem with this approach is the need to define a custom method to obtain the next and previous shoe sizes, but here is a question that can help you with that:
[What's the best way to implement `next` and `previous` on an enum type?
Try this
public String getShoeSize(double size) {
int s = (int)size;
String shoeSize = Integer.toString(s);
//check if it is a half value
if(size > s) {
shoeSize += " - 1/2";
}
return shoeSize;
}
At first convert value of double to string and split it:
double d=10.5;
String s = String.valueOf(d);
String[] newstr =s.split(".");
then if fraction is limited use switch case for .5 , .25 , .75
but it is not limited ,simplifying fractions is easy if you can folow the steps:
pay attention to this point that maybe your number is not point sign for example 10 that in switch case must be considered
1.find gcd of both num and den, so you have gcd=GCDFind(gcd, num);
2.now, if gcd==1, then the fraction cannot be simplified (it is already in simplified form).
3.if gcd > 1, then newNum = num/gcd; and newDen = den/gcd;
example for limited :
double s = 10.25;
String aString = Double.toString(s);
String[] fraction = aString.split("\\.");
int denominator = (int)Math.pow(10, fraction[1].length());
int numerator = Integer.parseInt(fraction[0] + "" + fraction[1]);
int t=numerator%denominator;
switch(t){
case 0: System.out.println(numerator/denominator);break; //example : 10
case 5: System.out.println(numerator/denominator + " - " +"1/2");break; //example : 10.5
case 25: System.out.println(numerator/denominator + " - " +"1/4");break; //example : 10.25
case 75: System.out.println(numerator/denominator + " - " +"3/4");break; //example : 10.75
default:System.out.println("Not in 1/2, 1/4 or 3/4");
}
The algorithm below converts hex to decimal, but I've confused, how this solution works?
public static int hex2decimal(String s) {
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
source
I had known only one approach to do that before I found out this one.
I mean, everyone knows:
X*16^Y where X is the number you want to convert and Y is the position for the number (begging from the end to the start).
So, if you want to convert DA145 to decimal would be...
*(5 * 16^0) + (4 * 16^1) + (1 * 16^2) + (10 * 16^3) + (13 * 16^4)*
This algorithm uses the fact that we can calculate 16^Y by repeatedly multiply together 16's and also that we can factor out common multiplications by 16. From your example you would instead end at:
13*16 + 10)*16 + 1)*16 + 4)*16 + 5
I've omitted the leading parentheses, as you see it happens to be that 13 is in effect multiplied with 16 four times.
The algorithm does pretty much the same as you would do it. It takes a String and compares every single char with the given value. This value is evaluated by digits, at which position it stands (e.g. A is in the 10th position, since we start counting with 0). This allows to easily change it e.g. to a 17 digit system instead of hexadezimal.
Edit: About the powers of 16, look at #skykings answer.
I am learning recursion and understanding most of it but this specific one baffles me, it is rather basic but I don't get which statement is the base case, I think it's the print line but obviously could be wrong. I know what the net result is but can't seem to follow how it does it step by step.
Code:
private static final String DIGIT_TABLE = "0123456789abcdef";
public static void printIt(long n, int base) {
if(n>=base)
printIt(n / base, base);
System.out.print(DIGIT_TABLE.charAt((int) n % base));
}
The base case is when n<base, or when the remaining number can be represented as a single digit in base base.
Here's an example of how the program would execute if the base were 16:
n_1: 0x1a5
n_2: 0x1a
n_3: 0x1
****
print n_3 % 16 -> 1
print n_2 % 16 -> a
print n_1 % 16 -> 5
At the point marked ****, the condition evaluates to false, so it doesn't go into infinite recursion.
If you are only looking for the base case or termination condition of the recurrence relation, then try this.
public static long printIt(long n, int base) {
if(n==0 || (base==0 || base==1)) return 0;
if(n>=base)
printIt(n / base, base);
long ln = DIGIT_TABLE.charAt((int) n % base);
return ln;
}
In an n-base number system, all the digits from 0-(n-1) can be represented in a single digit notation. For example, in a binary system (2-base), 0 and 1 can be represented as single digit and in a hexadecimal system (16-base), all numbers from 0-15 can be represented as single digit (a=10, b=11...f=15). Your program reduces the long n by dividing it by base till the time it becomes lesser than base and then prints its value in that base-base system. I assume the base here is 16 since your string is till 'f'. This means your method will print the MSB in hexadecimal representation of n. Note that if you store all the quotients of 'n/base', you will get the hexadecimal representation reversed.
I have a decimal number which I need to convert to binary and then find the position of one's in that binary representation.
Input is 5 whose binary is 101 and Output should be
1
3
Below is my code which only provides output as 2 instead I want to provide the position of one's in binary representation. How can I also get position of set bits starting from 1?
public static void main(String args[]) throws Exception {
System.out.println(countBits(5));
}
private static int countBits(int number) {
boolean flag = false;
if (number < 0) {
flag = true;
number = ~number;
}
int result = 0;
while (number != 0) {
result += number & 1;
number = number >> 1;
}
return flag ? (32 - result) : result;
}
Your idea of having countBits return the result, instead of putting a System.out.println inside the method, is generally the best approach. If you want it to return a list of bit positions, the analogue would be to have your method return an array or some kind of List, like:
private static List<Integer> bitPositions(int number) {
As I mentioned in my comments, you will make life a lot easier for yourself if you use >>> and get rid of the special code to check for negatives. Doing this, and adapting the code you already have, gives you something like
private static List<Integer> bitPositions(int number) {
List<Integer> positions = new ArrayList<>();
int position = 1;
while (number != 0) {
if (number & 1 != 0) {
positions.add(position);
}
position++;
number = number >>> 1;
}
return positions;
}
Now the caller can do what it wants to print the positions out. If you use System.out.println on it, the output will be [1, 3]. If you want each output on a separate line:
for (Integer position : bitPositions(5)) {
System.out.println(position);
}
In any case, the decision about how to print the positions (or whatever else you want to do with them) is kept separate from the logic that computes the positions, because the method returns the whole list and doesn't have its own println.
(By the way, as Alex said, it's most common to think of the lower-order bit as "bit 0" instead of "bit 1", although I've seen hardware manuals that call the low-order bit "bit 31" and the high-order bit "bit 0". The advantage of calling it "bit 0" is that a 1 bit in position N represents the value 2N, making things simple. My code example calls it "bit 1" as you requested in your question; but if you want to change it to 0, just change the initial value of position.)
Binary representation: Your number, like anything on a modern day (non-quantum) computer, is already a binary representation in memory, as a sequence of bits of a given size.
Bit operations
You can use bit shifting, bit masking, 'AND', 'OR', 'NOT' and 'XOR' bitwise operations to manipulate them and get information about them on the level of individual bits.
Your example
For your example number of 5 (101) you mentioned that your expected output would be 1, 3. This is a bit odd, because generally speaking one would start counting at 0, e.g. for 5 as a byte (8 bit number):
76543210 <-- bit index
5 00000101
So I would expect the output to be 0 and 2 because the bits at those bit indexes are set (1).
Your sample implementation shows the code for the function
private static int countBits(int number)
Its name and signature imply the following behavior for any implementation:
It takes an integer value number and returns a single output value.
It is intended to count how many bits are set in the input number.
I.e. it does not match at all with what you described as your intended functionality.
A solution
You can solve your problem using a combination of a 'bit shift' (>>) and an AND (&) operation.
int index = 0; // start at bit index 0
while (inputNumber != 0) { // If the number is 0, no bits are set
// check if the bit at the current index 0 is set
if ((inputNumber & 1) == 1)
System.out.println(index); // it is, print its bit index.
// advance to the next bit position to check
inputNumber = inputNumber >> 1; // shift all bits one position to the right
index = index + 1; // so we are now looking at the next index.
}
If we were to run this for your example input number '5', we would see the following:
iteration input 76543210 index result
1 5 00000101 0 1 => bit set.
2 2 00000010 1 0 => bit not set.
3 1 00000001 2 1 => bit set.
4 0 00000000 3 Stop, because inputNumber is 0
You'll need to keep track of what position you're on, and when number & 1 results in 1, print out that position. It look something like:
...
int position = 1;
while (number != 0) {
if((number & 1)==1)
System.out.println(position);
result += number & 1;
position += 1;
number = number >> 1;
}
...
There is a way around working with bit-wise operations to solve your problem.
Integer.toBinaryString(int number) converts an integer to a String composed of zeros and ones. This is handy in your case because you could instead have:
public static void main(String args[]) throws Exception {
countBits(5);
}
public static void countBits(int x) {
String binaryStr = Integer.toBinaryString(x);
int length = binaryStr.length();
for(int i=0; i<length; i++) {
if(binaryStr.charAt(i)=='1')
System.out.println(length-1);
}
}
It bypasses what you might be trying to do (learn bitwise operations in Java), but makes the code look cleaner in my opinion.
The combination of Integer.lowestOneBit and Integer.numberOfTrailingZeros instantly gives the position of the lowest 1-Bit, and returns 32 iff the number is 0.
Therefore, the following code returns the positions of 1-Bits of the number number in ascending order:
public static List<Integer> BitOccurencesAscending(int number)
{
LinkedList<Integer> out = new LinkedList<>();
int x = number;
while(number>0)
{
x = Integer.lowestOneBit(number);
number -= x;
x = Integer.numberOfTrailingZeros(x);
out.add(x);
}
return out;
}
I am trying to create a recursive method that uses Horner's algorithm to convert a fractional number in base n to base 10. I've searched here and all over but couldn't find anywhere that dealt with the fractional part in detail. As a heads up, I'm pretty weak in recursion as I have not formally learned it in my programming classes yet, but have been assigned it by another class.
I was able to make a method that handles the integer part of the number, just not the fractional part.
I feel like the method I've written is fairly close as it gets me to double the answer for my test figures (maybe because I'm testing base 2).
The first param passed is an int array filled with the coefficients. I'm not too concerned with the order of the coefficients as I'm making all the coefficients the same to test it out.
The second param is the base. The third param is initialized to the number of coefficients minus 1 which I also used for the integer part method. I tried using the number of coefficients, but that steps out of the array.
I tried dividing by the base one more time as that would give me the right answer, but it doesn't work if I do so in the base case return statement or at the end of the final return statement.
So, when I try to convert 0.1111 base 2 to base 10, my method returns 1.875 (double the correct answer of 0.9375).
Any hints would be appreciated!
//TL;DR
coef[0] = 1; coef[1] = 1; coef[2] = 1; coef[3] = 1;
base = 2; it = 3;
//results in 1.875 instead of the correct 0.9375
public static double fracHorner(int[] coef, int base, int it) {
if (it == 0) {
return coef[it];
}
return ((float)1/base * fracHorner(coef, base, it-1)) + coef[it];
}
Observe that fracHorner always returns a value at least equal to coef[it] because it either returns coef[it] or something positive added to coef[it]. Since coef[it] >= 1 in your tests, it will always return a number greater than or equal to one.
It's relatively easy to fix: divide both coef[it] by base:
public static double fracHorner(int[] coef, int base, int it) {
if (it == 0) {
return ((double)coef[it])/base;
}
return (fracHorner(coef, base, it-1) + coef[it])/base;
}