Negate int using XOR and addition - java

I have to write a method which converts an int value to the same negative int value. For example, if the user types in 5 the method should give back -5.
The whole story is:
The method has a transfer parameter which is either a positive or a negative int. Is it a positive int, we should change it to a negative int. If it is a negative int, do nothing.
It is also hard to check if the given int is positive or negative.
The regulations:
I'm only allowed to use the arithmetic operation + and all the boolean operations. But in this case I know that I have to use XOR.
It's not about writing the method and all the JAVA stuff. It's just the logic I struggle with.
How can I change a value to its negative value using only XOR and +?
ATTENTION:
The only operations allowed are:
!
^
&&
||
+
No *, no -, no ~
Edit:
The two solutions from CherryDT and MikeC are working well. Any ideas how to check if its a negative or a positive parameter with the same regulations? I thought this would be the easy part. Then realized it isn't.

(x ^ -1) + 1
Explanation: Basically, it's the same as ~x + 1. -1 has all bits set, and therefore inverts all bits when XORed with, just like NOT. And since, the other way round, inverting will always give you -x - 1, all you need to do is invert and add 1.

Here we go
public class Test {
public static void main(String []args){
int x = 245;
System.out.println(x);
x = (~x^x)*x;
System.out.println(x);
}
}

Related

trying to perform arithmetic operations on numbers expressed as a character string

I am obviously new to java. I have this assignment where I am supposed to write a program which performs arithmetic operations on numbers expressed as a character string.
I don't know where to start. I have tried googling, looking through my book, big java, in the relevant sections but can't seem to find helpful information.
I found a program that have completed the same assignment but I want to learn write my own and understand how to go about.
I can show you one of the methods that he used.
I have bolded a few comments where I get confused.
public static String add(String num1, String num2) {
while (num1.length() > num2.length()) {
num2 = "0" + num2;
}
while (num1.length() < num2.length()) {
num1 = "0" + num1;
}
int carry = 0; // whats the point of this?
String result = "";
// look at the for loop bellow. I don't understand why he is converting the strings to ints this
// way? this doesn't even return the correct inputed numbers?
for (int i = 1; i <= num1.length(); i++) {
int digit1 = Character.getNumericValue(num1.charAt(num1.length() - i));
int digit2 = Character.getNumericValue(num2.charAt(num2.length() - i));
int sum = digit1 + digit2 + carry;
carry = sum / 10;
result = (sum % 10) + result;
// why is he dividing the sum with 10? If the user inputs a 5, would't the result become 0.5
// which isn't a valid int value? this line is also confusing
}
if (carry > 0) {
result = carry + result;
}
return result;
}
Any explanation or even guidance to a page where I am trying to do is explained would be very appreciated.
I found a program that have completed the same assignment but I want to learn write my own and understand how to go about.
That is the right idea. I suggest that you stop looking at the code that you found. (I'm sure that your teachers don't want you to look up the answers on the internet, and you will learn more from your homework if you don't do it.)
So how to proceed?
(I am assuming that you are supposed to code the methods to do the arithmetic, and not just convert the entire string to a primitive number or BigInteger and use them to do the arithmetic.)
Here's my suggested approach:
What you are trying to program is the equivalent of doing long addition with a pencil and paper. Like you were taught in primary school. So I suggest that you think of that pencil-and-paper procedure as an algorithm and work out how to express it as Java code. The first step is to make sure that you have the steps of this algorithm clearly in your head.
Try to break the larger problem into smaller sub-problems. One sub-problem could be how to convert a character representing a decimal digit into an integer; e.g. how to convert '1' to 1. Next sub-problem is adding two numbers in the range 0 to 9 and dealing with the "carry". A final sub-problem is converting an integer in the range 0 to 9 into the corresponding character.
Write sample Java code fragments for each sub-problem. If you have been taught about writing methods, some of the code fragments could be expressed as Java methods.
Then you assemble the solutions to the sub-problems into a solution for the entire problem. For example, adding two (positive!) numbers represented as strings involves looping over the digits, starting at the "right hand" end.
As part of your program, write a collection of test cases that you can use to automate the checking. For example:
String test1 = add("8", "3");
if (!test1.equals("11")) {
System.out.println("test1 incorrect: expected '11' go '" +
test1 + "'");
}
Hints:
You can "explode" a String to a char[] using the toCharArray method. Or you could use charAt to get characters individually.
You can convert between a char representing a digit and an int using Character methods or with some simple arithmetic.
You can use + to concatenate a string and a character, or a character and a string. Or you can use a StringBuilder.
If you need to deal with signed numbers, strip off and remember the sign, do the appropriate computation, and put it back; e.g. "-123 + -456" is "- (123 + 456)".
If you need to do long multiplication and long division, you can build them up from long addition and long subtraction.
You can convert a number in String format to a number in numeric format by “long n = Long. parseLong(String)” or “Long n = Long.valueOf(String)”. Then just add 2 long variables using a + sign. It will throw NumberFormatException if the String is not a number but a character. Throw that exception back to the caller.
The first part of the code pads both numbers to equal lengths.
e.g. "45" + "789" will be padded to "045" + "789"
The for loop evaluates one character at a time, starting from the right hand most.
iteration 1 -> (right most)
5 + 9 -> 14
when you divide an integer with another integer, you will always get an integer.
hence carry = 14/10 = 1 (note: not 1.4, but 1, because an int cannot have decimal places)
and the remainder is 14 % 10 = 4 (mod operation)
we now concatenate this remainder into "result" (which is "" empty)
result = (14%10)+ result; // value of result is now "4"
iteration 2 -> (second right most)
4+8 + (carry) = 4 + 8 + 1 = 13
same thing, there is a carry of 13/10 = 1
and the remainder is 13%10 = 3
we concatenate the remainder into result ("4")
result = (13%10) + result = 3 +"4" = "34"
iteration 3->
0 + 7 + 1 = 8
this time 8/10 will give you 0 (hence carry = 0)
and 8%10 will give a remainder of 8.
result = 8 + "34" = "834"
after all the numbers have been evaluated, the code checks if there are anymore carry. if the value is more than 0, then that value is added to the front of the result.

Extracting BinaryString as Integer, need suggestions

PS: I tried searching many existing questions here on Stackoverflow, however it
only added chaos to my query!
10101
11100
11010
00101
Consider this as a sample Input, which I need to read as BinaryString one by one! Then I need to represent them as an Integer.
Obviously int x = 20 initializes x as a decimal Integer,
and I read from other questions that int y = 0b101 initializes y as a binary Integer.
Now, The question is: If I have a binaryString, how do I cast it into an int like with a preceding 0b . My objectives following this is to perform bit level OR and XOR operations.
ie from the above input, I need to do 10101 ^ 11100
Let me know if this is the right way to approach a problem like this, Thanks!
If I have understood your question correctly, you want to know how to represent Binary Strings as Integer.
Well, you can perform this task for conversion of Binary String to Integer:
String input = "0b1001";
String temp = input.substring(2);
int foo = Integer.parseInt(temp, 2);
Alternately, to switch back :
String temp = Integer.toBinaryString(foo);
from the above input, I need to do 10101 ^ 11100.
You can achieve the same using proper decimal representation of integer. If you want to re-invent the wheel, then
first convert the decimal representation of the given number to Binary String(using step 2);
then convert to integer value using step 1;
repeat steps 1 and 2 for the second number; and
finally, perform the XOR operation over them.
But, I don't see how it'll be performing/calculating differently. It'd still be stored as the same integer. It is just that you will get extra satisfaction(on your part) that the number was read as an integer and then converted to Binary representation of that number.
Try Integer.parseInt(String s, int radix). It will throw an exception if the binary string is invalid, so you might want to validate the input.
String binary = "10001";
int asInt = Integer.parseInt(binary, 2); // 17
int supports ^ (bitwise XOR) operator. All you have to do is convert your binary strings to int variables and perform the desired operations.

printf("%+f", ..) still shows negative number

I have a constant that's negative and I want the output to come out as positive. When I add a %+f it doesn't do anything and the output still comes out -15,123.45?
public static final double n2 = -15123.456789;
System.out.printf("%+,.2f\n", n2);
The format string "%+,.2f\n" only defines the formatting in which value must be printed. It doesn't change the actual value. If your input value is negative, the output string will display it as negative. It's like, when you make something bold, it doesn't change to another thing.
To convert the value to the opposite sign (- to +, + to -), you can multiply the value by -1: Thanks to kjbartel for the shortcut.
System.out.printf("%+,.2f\n", -1 * n2);
// or
System.out.printf("%+,.2f\n", -n2);
To convert the value to always be positive (- to +, + to +), you can use Math.abs: Thanks to zubergu for the tip.
System.out.printf("%+,.2f\n", Math.abs(n2));

+++x unexpected type required: variable found: value

This may be the silly question but i have no idea why it is so.I have written following code snippet.
public class Test {
public static void main(String... str)
{
int y = 9;
int z = +++y; //unexpected type required:variable found:value
int w = +-+y; // Not Error
}}
Why +-+y works and +++y Not ?
+++y is interpreted as the ++ operator followed by +y.
+y is as valid as -y is, but the ++ operator expects a variable to operate on (it cannot increment a value), and +y is considered a value (an addition operation was performed).
+-+y as 0 + (0 - (0 + y)), and it has no increment or decrement operators with in it, so even though the operation transform the whole expression into a value (instead of a variable reference) it has no effect.
In Java, the characters +++ mean ++, followed by +, which are two different operators. On the other hand, there is no operator +-, so the characters +-+ mean +, then -, then +.
If you want to play with these operators, there's also ~, which is a binary not. You can build arbitrary chains with the operators +, - and ~, as long as they don't contain ++ or --.

What is the modulo operator for longs in Java?

How do I find the modulo (%) of two long values in Java? My code says 'Integer number too large' followed by the number I'm trying to mod. I tried casting it to a long but it didn't work. Do I have to convert it to a BigInteger and use the remainder method? Thanks.
The % operator does work for longs. It sounds like you may have forgotten to stick L at the end of a numeric literal, as in 123456789L. Can we see your code?
You can only have an integer up to 2 147 483 647. If you want to go bigger than that, say 3 billion, you must specify it to be a long
class Descartes {
public static void main(String[] args) {
long orig = Long.MAX_VALUE;
long mod = orig % 3000000000; // ERROR 3000000000 too big
long mod = orig % 3000000000L; // no error, specified as a long with the L
}
}
Keep in mind that you can use capital OR lowercase L, but it's advisable to use capital, since the lowercase looks remarkably similar to the number 1.
You can also try working with the BigInteger class which has a remainder() method that works similarly to %.

Categories