What function does the ^
(caret) operator serve in Java?
When I try this:
int a = 5^n;
...it gives me:
for n = 5, returns 0
for n = 4, returns 1
for n = 6, returns 3
...so I guess it doesn't perform exponentiation. But what is it then?
What function does the ^
(caret) operator serve in Java?
When I try this:
int a = 5^n;
...it gives me:
for n = 5, returns 0
for n = 4, returns 1
for n = 6, returns 3
...so I guess it doesn't perform exponentiation. But what is it then?
That is because you are using the xor operator.
In java, or just about any other language, ^ is bitwise xor, so of course,
10 ^ 1 = 11. more info about bitwise operators
It's interesting how Java and C# don't have a power operator.
As others have said, it's bitwise XOR. If you want to raise a number to a given power, use
Math.pow(a , b)
, wherea
is a number andb
is the power.It is the Bitwise xor operator in java which results 1 for different value of bit (ie 1 ^ 0 = 1) and 0 for same value of bit (ie 0 ^ 0 = 0) when a number is written in binary form.
ex :-
To use your example:
The binary representation of 5 is 0101. The binary representation of 4 is 0100.
A simple way to define Bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.
0101 ^ 0100 = 0001 (5 ^ 4 = 1) .
The ^ operator in Java
^
in Java is the exclusive-or ("xor") operator.Let's take
5^6
as example:This the truth table for bitwise (JLS 15.22.1) and logical (JLS 15.22.2) xor:
More simply, you can also think of xor as "this or that, but not both!".
See also
Exponentiation in Java
As for integer exponentiation, unfortunately Java does not have such an operator. You can use
double Math.pow(double, double)
(casting the result toint
if necessary).You can also use the traditional bit-shifting trick to compute some powers of two. That is,
(1L << k)
is two to the k-th power fork=0..63
.See also
Horner's scheme
Addressing your specific need, you actually don't need to compute various powers of 10. You can use what is called the Horner's scheme, which is not only simple but also efficient.
Since you're doing this as a personal exercise, I won't give the Java code, but here's the main idea:
It may look complicated at first, but it really isn't. You basically read the digits left to right, and you multiply your result so far by 10 before adding the next digit.
In table form:
It is XOR operator. It is use to do bit operations on numbers. It has the behavior such that when you do a xor operation on same bits say 0 XOR 0 / 1 XOR 1 the result is 0. But if any of the bits is different then result is 1. So when you did 5^3 then you can look at these numbers 5, 6 in their binary forms and thus the expression becomes (101) XOR (110) which gives the result (011) whose decimal representation is 3.