Finding 1's complement - java

I am trying to make a program to calculate 1's complement after entering a binary number.
This is what I have to far:
import java.util.Scanner;
public class BitWiseComplement {
public static void main(String[] args) {
Scanner keysIn = new Scanner(System.in);
System.out.println("Please enter your number: ");
long originalNum = keysIn.nextLong();
System.out.println(~originalNum);
}
}
However, when I enter 0111011, I get -111012. I thought the ~ operator was supposed to invert the number so that all 0s are 1s and all 1s are 0s.
Any help?

You presumably want to work in binary, so try:
Scanner keysIn = new Scanner(System.in);
System.out.print("Please enter your number: ");
long originalNum = keysIn.nextLong(2); // specify radix of 2
System.out.println(Long.toBinaryString(~originalNum)); // print binary string
keysIn.close();
Please enter your number: 0111011
1111111111111111111111111111111111111111111111111111111111000100
As you can see, all bits are flipped. Bear in mind that there are leading 0s in front of the binary number you entered.

The ~ operator does what you think, but keep in mind that there are no unsigned types in Java, so when you enter a positive number (i.e., the high bit is a 0), applying ~ to it will make it negative (by turning the high bit on).
If you were to print the number out in hex (or binary, as other answers have suggested), you should see the answer you expect.

count the number of bits in num.
make a mask of 1s of the same length.
xor with the number to get the complement.
eg. 9^15=6
public static int solution(int num) {
int bits = Integer.toBinaryString(num).length();
int maxBound = (int)( Math.pow(2, bits)-1);
return num ^ maxBound;
}

Related

Way to get the twos compliment decimal from binary?

I have a simple question, how do I get the twos compliment instead of the regular answer from binary? I have a program that does the booths algorithm but when it returns the decimal it gives me a number that's a bit too high, I'm doing 9 * -9 and the answer it gives is 65455. I just want to know if there is a way to get the twos compliment instead (-81). The binary I get from the code is 1111111110101111 which I know from looking around does equal -81 when finding the two's compliment, I just don't know how to get my program to recognize or say that.
Edit: I found a small fix, essentially just checking if the binary of the product equals the result I got, this is how I've been printing the binary and converting it to a decimal, putting in the print area as The answer said something had to be done here, I got it working properly but would like to clean it up if I can
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first number: ");
int operand1 = sc.nextInt();
System.out.print("Enter the second number: ");
int operand2 = sc.nextInt();
String answer = multiply(operand1, operand2);
System.out.println("Final Product (binary): " + answer);
int decimal=Integer.parseInt(answer,2);
if(operand1 * operand2 < 0) {
int decProduct = operand1 * operand2;
String biProduct = toBinary(decProduct, 16);
if (biProduct.length() > 16)
{
biProduct = biProduct.substring(biProduct.length() - 16);
}
if(biProduct.equals(answer)) {
decimal = decProduct;
}
}
System.out.println("Final Answer (decimal): " + decimal);
}
The computer has no idea what it means. It just has some memory and in that memory are bits. The bits that are in it, are e.g. 1111111110101111.
What does that sequence mean? Who knows. The computer doesn't know or care.
It's the print code that decides. IT decides that this is to be taken in and then rendered such that the characters -, 8, and 1 appear on your computer screen.
Thus, the error here, is in the print code. There is no converting required. The bit sequence is all the things, at once: It's 1111111110101111, it's 65455, and it is -81. Which one is shown depends on how you print it.
Given that your print code isn't in the question, you're going to have to figure it out with this information.

Reading long binary numbers in java

I am trying to write a program which converts binary numbers into decimal, however as soon as I have a binary number which is bigger than 10 digits I get a java.lang.numberformatexception error. I was wondering how I should rewrite my code in order to handle binary numbers:
try{
//will throw an exception if the user's input contains a non-Integer
int inputNumber = Integer.parseInt(returnEnterNumber());
//when our user wants to convert from binary to decimal
if(binaryToDecimal.isSelected()){
//checks if number is binary
int checkNumber = inputNumber;
while (checkNumber != 0) {
if (checkNumber % 10 > 1) {
throw new InvalidBinaryException();
}
checkNumber = checkNumber / 10;
}
//converts from binary and outputs result
int n = Integer.parseInt(returnEnterNumber(), 2);
displayConvertedNumber(Integer.toString(n));
}
}
catch(Exception e) {
displayConvertedNumber("WRONG INPUT! - TRY again");
}
Edit: I understand why the code fails, seeing as how it takes the number as a decimal and overflows. I am not sure how to rewrite the code to take the input as a binary straight away.
That's not a valid way to check a binary number. You're converting to an int in base 10, then checking that each of the digits in base 10 is zero or one. The conversion itself will fail on long enough input strings, and if it doesn't the checking will fail as well.
You shouldn't be converting it all all, you should be checking the input string itself.
EDIT Actually you don't have to do anything. Integer.parseInt() will check it for you and throw NumberFormatException if the string isn't a number in the specified radix.
You are parsing your binary digit string as a decimal integer first. If it has more than 10 significant digits then its decimal interpretation is too big to fit in an int, so the decimal conversion fails.
When you are going to parse the digit string as a binary number, simply avoid first parsing it as a decimal one. For instance, most of what you posted could be reduced to this:
int inputNumber = Integer.parseInt(returnEnterNumber(),
binaryToDecimal.isSelected() ? 2 : 10);
Take a look at Integers MAX values:
public class MainClass {
public static void main(String[] arg) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
}
}
the output will be:
2147483647
-2147483648
This means that if you have more than 10 digits, you have exceeded the max number for the Integer data type.
Try Using BigInteger on your binary value or consider returning it as String
Here is one line of code that will accomplish what you are looking for
System.out.println(new BigInteger("10101010101010111101010101001101010101010101001010101010101001011101010101010101",2).toString());

Counting decimal numbers in Java

I have an issue where i am trying to count the amount of numbers with a decimal point however it is just counting whenever there is an integer even if it is a whole one.
Scanner cd = new Scanner(name); // count double
Scanner cn = new Scanner(name).useDelimiter("[^0-9]+"); // count int
while(cn.hasNextInt()) {
cn.nextInt();
numberOfInts++;
}
while(cd.hasNextDouble()) {
cd.nextDouble();
numberOfDecimals++;
}
so yeah the number of decimals justs counts whenever a integer is scanned, even if it is a whole number, i want it too just count numbers with a decimal point.

Add two Integers up to 50 digits

This is the actual question:
Write an interactive program that adds two integers of up to 50 digits each
(Represents integer as an array of digits).
This is a homework question and the language to be used is Java. I got this far but I don't think it is even close.
1. It is not taking input more than 20 digits but have to work with 50 digits.
2. The method 'integerToDigits' is producing two arrays but i am unable to sort out how to use them and add them in the main method.
Help please.
package One;
import java.util.Scanner;
public class AddInt {
public static void main(String[] args) {
Long x,y;
Long a[] = new Long[50];
Long b[] = new Long[50];
System.out.println("Please enter two numbers which have no more than 50 digits: ");
Scanner s = new Scanner(System.in);
x = s.nextLong();
y = s.nextLong();
System.out.println(x+ "and "+y);
integerToDigits(x);
integerToDigits(y);
}
public static Long[] integerToDigits(Long n){
Long digits[] = new Long[50];
Long temp = n;
for(int i = 0; i < 50; i++){
digits[49-i] = temp % 10;
temp /= 10;
}
return digits;
}
}
It is not taking input more than 20 digits but have to work with 50 digits.
This is because you're using x = s.nextLong() which is trying to convert the input to a long. The maximum long value is 9223372036854775807 which is nowhere near 50 digits. You'll need to get the input as a String and then covert that to your int[]
The method 'integerToDigits' is producing two arrays, but I am unable to sort out how to use them and add them in the main method.
In terms of adding up the arrays of digits, you can use the same process we learn very early on in school.
Add the units, then carry over any tens.
Add the tens and carry over any hundreds.
Add the hundreds and carry over any thousands.
...
This process can be iterated adding each order of magnitude with the carry over from the previous one.
Hopefully those tips give you a way to solve your problem.
If you do want a solution, I've produced one here that seems to work as you require. (Although not in ideone apparently)
If "Represents integer as an array of digits" is a suggestion and not a requirement a solution using BigInteger would look something like:
// read numbers from input
// store first value as String "firstNumber"
// store second value as String "secondNumber"
BigInteger a = new BigInteger(firstNumber);
BigInteger b = new BigInteger(secondNumber);
BigInteger result = a.add(b);
System.out.println("Result is " + result.toString());
If "Represents integer as an array of digits" is a requirement, well, then it's a silly assignment :) No one would store an integer like that. Worst case, I'd store it as a String if BigInteger was not allowed.

Convert fraction to decimal number

i'm doing some exercises in my Java book. I'm very new to programming. Therefore, notice (in the code) that i'm still on Chapter one. Now I already did everything, I just want a confirmation if this is legitimate so I can feel free to move on next.
If not, I would sincerely appreciate to not do my code for me; I want advice.
Here's the question written in the book,
"Write an application that prompts/reads the numerator and denominator of a fraction as integers, then prints the decimal equivalent of the fraction."
I'll illustrate this sentence with my code:
I did a revision here. Is this one OK?..
import java.util.*;
public class ExerciseEleven {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
double fraction;
int fractionValue;
int decimal;
double value;
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
fraction = (double) numerator / denominator;
fractionValue = (int) (fraction * 10);
decimal = fractionValue % 10;
value = decimal * 0.1;
System.out.println(value);
}
}
It compiles and works fine.
Thank you.
It doesn't do what task says it should. You read doubles instead of integers, and the decimal equivalent is not what you print out. Decimal equivalent for 1/2 is 0.5. And you print 5.
Also, you can pay attention to your code style: variable names are usually written in lowerCamelCase, like that : simpleVariable.
Update
now it prints what you need. However you do it not in the very right way and your indentation can still be improved.
It's fine (I didn't read the assignment very well, did I? Kudos to Vladimir.) ...but some comments:
Usually you want to indent methods within the class.
Standard practice is to use initial caps (Numerator) only for types (e.g., classes, interfaces, enums). Variable, field, and method names should start with a lower-case letter. Now, you're free to ignore standard practice, but if you do people will have a lot of trouble reading your code. :-)
For rounding, you probably want to look at Math.round rather than truncating with a cast. But the assignment didn't say anything about rounding.
You might want to handle the case where denominator is zero.
So keeping those in mind:
import java.util.*;
public class ExcerciseEleven {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
if (denominator == 0) {
System.out.println("Can't divide by zero");
}
else {
double fraction = (double)numerator / denominator;
System.out.println(fraction);
}
}
}
Hey I am doing some thinking about this and I have noticed something interesting after looking at this source and here is the Algorithm that I plan on implementing
First I will convert the number from the Metric using the
Javax.Measure family of functions and I will get a number like
0.3750
Then I will divide the number by ONE_SIXTEENTH which = 0.0625
ONE_SIXTEENTH = 0.0625
The answer 0.3750 / ONE_SIXTEENTH = 6;
So now I know there are 6 sixteenths of the inch
Next I check to see if 6 is divisible by 4, 6/4 = 1.5 ie not a whole number so the fraction is still regarded as 6/16th of an inch for now
Next I check to see if 6 is divisible by 2, 6/2 = 3
This is a whole number so we will use it to reconstitute the fraction
So now that we have divided 6 by 2 and gotten 3 the 16 needs to be divided by 2 and we end up with 8 so 6/16th of an inch becomes 3/8th of an inch.
PS Has anyone noticed that this is similar to a fizz bang program?
____________________________________________
Here is the chart which helped me get my head around this
My workings
There are three important parts of division operation :
Sign of the result.
Integral part
Decimal part
Also, there are few corner cases where you need to deal with the fact that Integer.MIN_VALUE is greater than Integer.MAX_VALUE when compared in absolute form.
For example : -2147483648/-1 can't yield 2147483648 when divided in the form of integer types. The reason is simple. The type of the resulting type will be integer type, and the maximum positive value that a integer type variable can hold is +2147483647
To mitigate that scenario, we should at first convert both the numerator and denominator into their long positive form. That gives us the integral part of the answer.
The XOR of two numbers will have the sign bit as 1 only in case they have opposite signs. That solves the first part (sign of result) of the problem.
For decimal part, we can employ the general division rule i.e. multiply the remainder with 10 and try dividing again and repeat. Keep record of the remainder we have already come across to prevent the loop from going into unbounded iterations.
public String fractionToDecimal(int A, int B) {
StringBuilder sb = new StringBuilder((A^B) < 0 ? "-" : "");
long a = Math.abs((long)A);
long b = Math.abs((long)B);
sb.append(Long.toString(a/b));
long rem = a % b;
sb.append((rem != 0) ? "." : "");
Map<Long, Integer> remainderMap = new HashMap<>();
int pos = 0;
while (rem != 0){
sb.append(Long.toString((rem*10)/b));
remainderMap.put(rem, pos++);
rem = (rem*10) % b;
if (remainderMap.containsKey(rem)){
String currNum[] = sb.toString().split("\\.");
return currNum[0] + "." + currNum[1].substring(0, remainderMap.get(rem)) +
"(" + currNum[1].substring(remainderMap.get(rem)) + ")";
}
}
if (sb.toString().equals("-0")) return "0";
return sb.toString();
}
Sample output :
2/3 gives 0.(6)
-2147483648/-1 gives 2147483648

Categories

Resources