I need to write a method for comparing two binary numbers. I am storing the binary numbers in character arrays, so I can store big numbers (I can't use the BigInteger class or any other packages).
Example to make things clear:
char[] num1 = {'1','1','0'}
char[] num2 = {'1','1','1'}
I need to return 0 if they are equal, -1 if a < b and 1 if a > b
This is the approach I took:
static int compare(char[]a, char[]b) {
//If arrays lengths aren't equal I already know, one is bigger then the other
int a_len = a.length;
int b_len = b.length;
int a_bits = 0;
int b_bits = 0;
if (a_len > b_len)
return 1;
if (b_len > a_len)
return -1;
//I count the number of bits that are 1 in both arrays
for (int i = 0; i < a.length; i++) {
if (a[i] == '1') a_bits++;
if (b[i] == '1') b_bits++;
}
if(a_bits>b_bits)
return 1;
if(b_bits>a_bits)
return -1;
return 0;
}
So as far as I understand, this works in every case, but the case where the number of bits are equal (1100 is bigger than 1001 for example).
I was thinking I could add up the indexes in the for loop for each array and work from there, but I started thinking I may be overcomplicating things. Is this even a good approach to it? I'm starting to doubt it. Any insight is appreciated
I would look for the first index that is 1 in one of the numbers but 0 in the other number. You can replace the bit counting loop(keeping the length check) with:
for (int i = 0; i < a.length; i++) {
if (a[i] == '1' && b[i] == '0') return 1;
if (b[i] == '1' && a[i] == '0') return -1;
}
return 0;
Using some conversion and the binary parseInt offered by class Integer you can do this simple comparison regardless of the arrays' size. (I'd be careful instead with checking the length of the arrays because if you have leading zeros in one array this could bring some comparisons to miss).
String first = new String(a);
String second = new String(b);
int firstint = Integer.parseInt(first, 2);
int secondint = Integer.parseInt(second, 2);
if(firstint > secondint)
return 1;
if(firstint < secondint)
return -1;
return 0;
An alternative approach would be as follows:
Convert Array Of Characters into String.
Convert the resulting String into int.
Work out the logic from the resulting int
It will always work and you can print out the resulting conversion.
Hope this helps.
public static void main(String[] args) {
char[] num1 = {'1','1','0'};
char[] num2 = {'1','1','1'};
System.out.println(compare(num1, num2));
}
public static int compare(char[]num1, char[]num2) {
// Convert Array of Characters to String
String one = String.valueOf(num1);
String two = String.valueOf(num2);
// Convert to Integer (Binary to Decimal Conversion to base2)
int a = Integer.parseInt(one,2);
int b = Integer.parseInt(two,2);
int result = 0; // return result as equals i.e. 0.
if(a > b) { // Yes. Curly brackets are important in Java
result = 1;
} else if(a < b){
result = -1;
}
return result; // Use only one return, i.e. a variable.
}
Related
I'm writing a method for my CS151 class called countSevens(n). It Returns count how many digits are 7 in the given number n. This is what I have so far but I'm doing something wrong that I can't figure out.
public int countSevens(int n){
int count = 0;
String strI = Integer.toString(n);
for (int i = 0; i < strI.length(); i++){
if(strI.substring(i).equals("7")){
count++;
}
}
return count;
}
You can do it with java streams
public int countSevens(int n) {
return (int) String.valueOf(n).chars().filter(ch -> ch == '7').count();
}
(int) - cast to an int type, in this particular case it safe to cast long to int, because we can't get a conversation error. In other cases it's better to use Math.toIntExact(long)
String.valueOf(n) - convert to string
chars() - return stream of chars
filter(ch -> ch == '7') - filter all chars that equals to 7
count() - returns the count of elements in this stream
strI.substring(i)
Will return the part of string from i-character to the end.
Use strI.charAt(i) instead
From the definition of String.substring(int):
Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
So this will only count the last instance of a 7 in your number, and only if it's the last digit in the number.
Instead, try this:
if(strI.substring(i, i+1).equals("7"))
Or, since you're dealing with ints, you can avoid using strings altogether. n % 10 will get you the last digit, and n /= 10 will bump the entire number right by one digit. That should be enough to get you started on doing this without Strings.
To count the number of 7s in an integer:
int counter = 0;
int number = 237123;
String str_number = String.valueOf(number);
for(char c : str_number.toCharArray()){
if(c == '7'){
counter++;
}
}
You can just use simple arithmetics:
public static int countSevens(int i) {
int count = 0;
for (i = i < 0 ? -i : i; i != 0; count += i % 10 == 7 ? 1 : 0, i /= 10);
return count;
}
But who can read this? Not many, so here is a cleaner solution, applying the same logic:
public static int countSevens(int i) {
int count = 0;
// ignore negative numbers
i = Math.abs(i);
while(i != 0) {
// if last digit is a 7
if(i % 10 == 7) {
// then increase the counter
count++;
}
// remove the last digit
i /= 10;
}
return count;
}
New to programming: In Java, what is the best way to get each individual digit of an Integer and its position for comparisons? For example, with an input of an Integer i = 12345, I'd like to preform a comparison operation on each individual digit 1, 2, 3, 4, and 5. Since I can't get the index of the integer, I converted the integer to string, iterated, and used charAt().
String sI = Integer.toString(i);
for(int j = 0; j<i; j++){
if(charAt(j)>n){
//do something
}
}
why not try this... you will know that your int is printing from the last digit so you'll know the position.
public static void main(String[] args) {
Integer temp = 123456789;
do {
System.out.println(temp % 10);
temp = temp / 10;
} while (temp % 10 > 0);
}
I would do the same solution however your loop may result in some unexpected errors. That's because i can be greater than the length of your String sI.
And chars in Java are integers too so the comparison may fail: for example the character value of 1 is 49 so a comparison like if (sI.charAt(j) > 10) will always results in true. So you have to re-convert your character to an integer with the Character.getNumericValue() function.
So I'd change the loop to the following:
String sI = Integer.toString(i);
for(int j = 0; j < sI.length(); j++){
if(Character.getNumericValue(sI.charAt(j)) > n){
//do something
}
}
May be something like this helps
public int findallIntegers(int x, int n) {
if(x < 1) return 1;
if(x%10 > n) {
//do some thing
}
return findallIntegers(x/10, n);
}
I am supposed to write a compare method that essentially does what the compareTo method does. I have written the code but it does not compare strings of different length.
This is my code:
public static int compare(String a, String b)
{
int result = 0;
a = a.toLowerCase();
b = b.toLowerCase();
//program assumes strings are equal
for (int i = 0; i<a.length() && i<a.length(); i++) {
int c = a.charAt(i);
int d = b.charAt(i);
if (c < d){
result = -1;
break;
}
if (a.length() > b.length()) {
result = -1;
break;
}
if (a.length() < b.length()) {
result = +1;
break;
}
if (c > d) {
result = 1;
break;
}
}
return result;
}
I have done an if loop comparing 2 strings of different lengths but, yet, the program ignores that.
Im trying to understand my mistake so please don't just give me the answer without explaining for I will not learn anything.
Thanks, in advance.
First, you want to make sure, when comparing character by character, that i is less than both a's length and b's length. Right now, you're comparing i to a's length twice.
Try:
// *
for (int i = 0; i<a.length() && i<b.length(); i++){
Second, you only want to compare lengths if you have compared each character equal until one of them has ended. Place the length comparisons after the for loop.
Third, "mars" comes before "marshall", so if a's length is less than b's length, then it compares less also.
// After the for loop ends:
if(a.length() > b.length()){
result = 1;
break; }
if(a.length() < b.length()){
result = -1;
break;
I'm trying to convert an integer to a 7 bit Boolean binary array. So far the code doesn't work:
If i input say integer 8 to be converted, instead of 0001000 I get 1000000, or say 15 I should get 0001111 but I get 1111000. The char array is a different length to the binary array and the positions are wrong.
public static void main(String[] args){
String maxAmpStr = Integer.toBinaryString(8);
char[] arr = maxAmpStr.toCharArray();
boolean[] binaryarray = new boolean[7];
for (int i=0; i<maxAmpStr.length(); i++){
if (arr[i] == '1'){
binaryarray[i] = true;
}
else if (arr[i] == '0'){
binaryarray[i] = false;
}
}
System.out.println(maxAmpStr);
System.out.println(binaryarray[0]);
System.out.println(binaryarray[1]);
System.out.println(binaryarray[2]);
System.out.println(binaryarray[3]);
System.out.println(binaryarray[4]);
System.out.println(binaryarray[5]);
System.out.println(binaryarray[6]);
}
Any help is appreciated.
There's really no need to deal with strings for this, just do bitwise comparisons for the 7 bits you're interested in.
public static void main(String[] args) {
int input = 15;
boolean[] bits = new boolean[7];
for (int i = 6; i >= 0; i--) {
bits[i] = (input & (1 << i)) != 0;
}
System.out.println(input + " = " + Arrays.toString(bits));
}
I would use this:
private static boolean[] toBinary(int number, int base) {
final boolean[] ret = new boolean[base];
for (int i = 0; i < base; i++) {
ret[base - 1 - i] = (1 << i & number) != 0;
}
return ret;
}
number 15 with base 7 will produce {false, false, false, true, true, true, true} = 0001111b
number 8, base 7 {false, false, false, true, false, false, false} = 0001000b
Hints: Think about what happens when you get a character representation that's less than seven characters.
In particular, think about how the char[] and boolean[] arrays "line up"; there will be extra elements in one than the other, so how should the indices coincide?
Actual answer: At the moment you're using the first element of the character array as the first element of the boolean array, which is only correct when you're using a seven-character string. In fact, you want the last elements of the arrays to coincide (so that the zeros are padded at the front not at the end).
One way to approach this problem would be to play around with the indices within the loop (e.g. work out the size difference and modify binaryarray[i + offset] instead). But an even simpler solution is just to left pad the string with zeros after the first line, to ensure it's exactly seven characters before converting it to the char array.
(Extra marks: what do you do when there's more than 7 characters in the array, e.g. if someone passes in 200 as an argument? Based on both solutions above you should be able to detect this case easily and handle it specifically.)
What you get when you do System.out.println(maxAmpStr); is "1000" in case of the 8.
So, you only get the relevant part, the first "0000" that you expected is just ommitted.
It's not pretty but what you could do is:
for (int i=0; i<maxAmpStr.length(); i++)
{
if (arr[i] == '1')
{
binaryarray[i+maxAmpStr.length()-1] = true;
}
else if (arr[i] == '0')
{
binaryarray[i+maxAmpStr.length()-1] = false;
}
}
Since nobody here has a answer with a dynamic array length, here is my solution:
public static boolean[] convertToBinary(int number) {
int binExpo = 0;
int bin = 1;
while(bin < number) { //calculates the needed digits
bin = bin*2;
binExpo++;
}
bin = bin/2;
boolean[] binary = new boolean[binExpo]; //array with the right length
binExpo--;
while(binExpo>=0) {
if(bin<=number) {
binary[binExpo] = true;
number =number -bin;
bin = bin/2;
}else {
binary[binExpo] = false;
}
binExpo--;
}
return binary;
}
The char-array is only as long as needed, so your boolean-array might be longer and places the bits at the wrong position. So start from behind, and when your char-array is finished, fill your boolean-array with 0's until first position.
Integer.toBinaryString(int i) does not pad. For e.g. Integer.toBinaryString(7) prints 111 not 00000111 as you expect. You need to take this into account when deciding where to start populating your boolean array.
15.ToBinaryString will be '1111'
You are lopping through that from first to last character, so the first '1' which is bit(3) is going into binaryArray[0] which I'm assuming should be bit 0.
You ned to pad ToBinaryString with leading zeros to a length of 7 (8 ??)
and then reverse the string, (or your loop)
Or you could stop messing about with strings and simply use bit wise operators
BinaryArray[3] = (SomeInt && 2^3 != 0);
^ = power operator or if not (1 << 3) or whatever is left shift in Java.
public static boolean[] convertToBinary(int b){
boolean[] binArray = new boolean[7];
boolean bin;
for(int i = 6; i >= 0; i--) {
if (b%2 == 1) bin = true;
else bin = false;
binArray[i] = bin;
b/=2;
}
return binArray;
}
public static String intToBinary(int num) {
int copy = num;
String sb = "";
for(int i=30; i>=0; i--) {
sb = (copy&1) + sb;
copy = copy >>>=1;
}
return sb;
}
AND the number with 1
Append the vale to a string
do unsigned right shift
repeat steps 1-3 for i=30..0
String maxAmpStr = Integer.toBinaryString(255);
char[] arr = maxAmpStr.toCharArray();
boolean[] binaryarray = new boolean[20];
int pivot = binaryarray.length - arr.length;
int j = binaryarray.length - 1;
for (int i = arr.length - 1; i >= 0; i--) {
if (arr[i] == '1') {
binaryarray[j] = true;
} else if (arr[i] == '0') {
binaryarray[j] = false;
}
if (j >= pivot)
j--;
}
System.out.println(maxAmpStr);
for (int k = 0; k < binaryarray.length; k++)
System.out.println(binaryarray[k]);
}
I want to convert decimal numbers to binary numbers. I want to store them in an array.
First I need to create an array that has a certain length so that I can store the binary numbers. After that I perform the conversion, here is how I do it:
public class Aufg3 {
public static void main(String[] args) {
int[] test = decToBin(12, getBinArray(12));
for(int i = 0; i < test.length; i++){
System.out.println(test[i]);
}
}
public static int[] getBinArray(int number){
int res = number, length = 0;
while(res != 0){
res /= 2;
length++;
}
return new int[length];
}
public static int[] decToBin(int number, int[] array){
int res = number, k = array.length-1;
while(res != 0){
if(res%2 == 0){
array[k] = 0;
}else{
array[k] = 1;
}
k--;
res /= 2;
}
return array;
}
}
Is there anything to improve? It should print 1100 for input of 12.
Why not just use the toBinaryString method of the Integer class:
System.out.println(Integer.toBinaryString(12))
I assume you want to write your own code -- otherwise this is straightforward to do using methods from the standard Java library.
Some quick comments:
You can get rid of the res temp vars. Work directly on number (remember that Java passes parameters by value).
Shift is more efficient than division (number >>>= 1 instead of number /= 2), although the compiler should be able to optimize this anyway
You can avoid the modulus in decToBin if you just do array[k] = number & 1;
While you are at it, why not call getBinArray from decToBin directly? Then you can call decToBin with only one arg -- the value to convert.
Here is a slightly optimized version of your code:
public static int[] getBinArray(int number) {
int length = 0;
while (number != 0) {
number >>>= 1;
length++;
}
return new int[length];
}
public static int[] decToBin(int number) {
int[] array = getBinArray(number);
int k = array.length-1;
while (number != 0)
{
array[k--] = number & 1;
number >>>= 1;
}
return array;
}
If this isn't homework, no need to do it yourself. The following code should work:
BigInteger bigInt = new BigInteger(number);
String asString = bigInt.toString(2);
There might be more efficient ways, but this is certainly very readable and maintainable.
There are some small things that you can improve:
You should define a "high-level" method that converts an int to an int[]. In the current code you have to mention the 12 two times, which is bad.
You should use a do { ... } while (number != 0) loop. Otherwise the number 0 will be represented by an empty array.
You should use x >>> 1 instead of x / 2, since that handles negative numbers correctly.
If you want to check that your code is correct, write another method that converts back from binary to int. Then you can check that binToDec(decToBin(12, ...)) == 12.
The method getBinArray should not be public, since it is only a helper method. You can either replace the public with private or just remove the public.