Download 02. Java Features

Document related concepts
no text concepts found
Transcript
Contest Algorithms
January 2016
2. Java Features
Look at some features of Java
used in many competition
problems.
Contest Algorithms: 2. Java Features
1
Overview
 1. Multi-dimensional Arrays
 2. Arrays class: sort, binary search, comparators
 3. Strings
 4. Regular Expressions
 5. Bitwise Ops
Contest Algorithms: 2. Java Features
2
1. Multi-dimensional Arrays (2D/3D)
 Use a two-dimensional array to represent a matrix or a
table.
Contest Algorithms: 2. Java Features
3
Array Features
 An array is the fastest way to do random access to data
 But an array's size is fixed
 If it runs out of space, you have to create a new array and
copy everything over, which is slow
Fill an Integer Matrix
import java.io.*;
import java.util.*;
see UseGraph.java
in Part 1
public class UseGraph // use Main in contests
{
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new File("graphData.txt"));
// for testing
int numVs = sc.nextInt();
int[][] adjMat = new int[numVs][];
for (int i = 0; i < numVs; i++) {
adjMat[i] = new int[numVs];
for (int j = 0; j < numVs; j++)
adjMat[i][j] = sc.nextInt();
} Algorithms
Contest
:
// use numVs as no. of rows
// create ith row array
// fill row
5
Two-dimensional Arrays
0 1
2
3
4
0 1
2
3
4
0
0
0
0
1
1
1
2
2
2
3
3
4
4
matrix = new int[5][5];
matrix.length ==
7
3
matrix[2][1] = 7;
5
matrix[0].length == 5
1
1
2
2
3
4
5
6
7
8
9
10
11
12
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
no. rows
array.length ==
4
no. columns
array[0].length == 3
6
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
==
Contest Algorithms: 2. Java Features
int[][] array
array[0][0] =
array[1][0] =
array[2][0] =
array[3][0] =
= new int[4][3];
1; array[0][1] = 2; array[0][2] =
4; array[1][1] = 5; array[1][2] =
7; array[2][1] = 8; array[2][2] =
10; array[3][1] = 11; array[3][2]
3;
6;
9;
= 12;
7
Lengths of Two-dimensional Arrays
int[][] x = new int[3][4];
x
x[0][0] x[0][1] x[0][2] x[0][3]
x[0].length is 4
x[1][0] x[1][1] x[1][2] x[1][3]
x[1].length is 4
x[2][0] x[2][1] x[2][2] x[2][3]
x[2].length is 4
x[0]
x[1]
x[2]
x.length is 3
8
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
array[4].length
array.length
array[0].length
array[1].length
array[2].length
array[3].length
ArrayIndexOutOfBoundsException
9
Ragged Arrays
 Each row in a two-dimensional array is itself an
array. So, the rows can have different lengths.
Such an array is known as a ragged array.
int[][] matrix = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5},
{3, 4, 5},
{4, 5},
{5}
};
matrix.length is 5
matrix[0].length is 5
matrix[1].length is 4
matrix[2].length is 3
matrix[3].length is 2
matrix[4].length is 1
10
int[][] triangleArray = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5},
{3, 4, 5},
{4, 5},
{5}
};
1 2 3 4
5
2 3 4 5
3 4 5
4 5
5
11
Initializing arrays with random values
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++)
matrix[row][col] = (int)(Math.random() * 100);
}
12
Summing all elements
int total = 0;
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++)
total += matrix[row][col];
}
13
Summing elements by column
for (int col = 0; col < matrix[0].length; col++) {
int total = 0;
for (int row = 0; row < matrix.length; row++)
total += matrix[row][col];
System.out.println("Sum for column " + col + " is "
}
+ total);
14
Random shuffling
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
int i1 = (int)(Math.random() * matrix.length);
int j1 = (int)(Math.random() * matrix[i].length);
// Swap matrix[i][j] with matrix[i1][j1]
int temp = matrix[i][j];
matrix[i][j] = matrix[i1][j1];
matrix[i1][j1] = temp;
}
}
15
Three-dimensional Arrays
double[][][] scores = new double[10][5][2];
16
Basic Matrix Functions
 Matrix.java contains methods for
creating 2D matricies of doubles,
adding, multiplying, taking powers,
etc.
 Also Gaussian Elimination
Matrix(int M, int N)
Matrix(double[][] data)
Matrix(double[] arr, int side)
int getRows()
int getCols()
double[][] getData()
void setElem(int i, int j, double val)
double getElem(int i, int j)
Matrix transpose()
Matrix add(Matrix B)
Matrix subtract(Matrix B)
boolean eq(Matrix B)
Matrix multiply(Matrix B)
Matrix power(long exp)
double[] flatten()
Matrix solve(Matrix rhs)
void print()
// static methods
Matrix random(int M, int N)
Matrix identity(int N)
Contest Algorithms: 2. Java Features
see Matrix.java
17
Usage
public static void main(String[] args)
{
double[][] d = { { 1, 2, 3 }, { 4, 5, 6 }, { 9, 1, 3} };
Matrix D = new Matrix(d);
D.print();
System.out.println("Value at (0,1): " + D.getElem(0,1));
Matrix A = Matrix.random(5, 5);
A.print();
Matrix B = A.transpose();
B.print();
Matrix C = Matrix.identity(5);
C.print();
A.add(B).print();
B.multiply(A).print();
// shouldn't be equal since AB != BA in general
System.out.println( A.multiply(B).eq(B.multiply(A)) );
Contest Algorithms: 2. Java Features
Matrix b = Matrix.random(5, 1);
b.print();
Matrix x = A.solve(b);
x.print();
A.multiply(x).print();
} // end of main()
18
Boolean Matrix
 There's also a less fully-featured boolean matrix class
 see BoolMat.java
 It illustrates how to implement 'add' and 'multiply' for
boolean values
 'add' uses boolean OR (||)
 multiply uses boolean AND (&&)
Contest Algorithms: 2. Java Features
19
2. Arrays class
 A set of static utility methods
 fill(): fill an array with a value
 equals(): compare two arrays for equality
 Probably most useful are:
static void sort(Object [] a);
static void sort(Object [] a, Comparator c);
static int binarySearch(Object [] a, Object key);
static int binarySearch(Object [] a, Object key, Comparator c)
Arrays.sort()
see GenericSorting.java
 Sorts the objects into ascending order
 A stable sort:
 equal elements are not reordered
 You can specify a range
 fromIndex to toIndex-1
 The objects need to have a Comparator class
 or implement Comparable
The Comparator Interface
interface COMPARATOR<T>
java.util
Methods
int compare(T x, T y)
Compares its two arguments for order. Returns a
negative integer, zero, or a positive integer to
specify that x is less than, equal to, or greater than
y.
boolean equals(Object obj)
Returns true if this object equals obj and false
otherwise.
continued
Comparing Circles
public class Circle
{
private double xCenter, yCenter;
private double radius;
public Circle(double x, double y, double r)
{ xCenter = x; yCenter = y;
radius = r;
}
public double getX()
{ return xCenter; }
:
see Circle.java
public double getY()
{ return yCenter; }
public double getRadius()
{ return radius; }
public double getArea()
{ return Math.PI * radius * radius;
:
}
}
// more methods, but no comparison function
// end of Circle class
Comparing Circle Radii
public class RadiiComp implements Comparator<Circle>
{
public int compare(Circle c1, Circle c2)
{
double radC1 = c1.getRadius();
double radC2 = c2.getRadius();
}
// returns < 0 if radC1 < radC2,
//
0 if radC1 == radC2,
//
> 0 if radC1 > radC2
return (int)(radC1 – radC2);
// end of compare()
// equals() is inherited from Object superclass
}
// end of RadiiComp class
see RadiiComp.java
Comparing Circle Positions
public class DistComp implements
{
public int compare(Circle c1,
{
double c1Dist = (c1.getX()
(c1.getY()
double c2Dist = (c2.getX()
(c2.getY()
}
}
Comparator<Circle>
Circle c2)
*
*
*
*
c1.getX()) +
c1.getY());
c2.getX()) +
c2.getY());
// returns < 0 if c1Dist < c2Dist,
//
0 if c1Dist == c2Dist,
//
> 0 if c1Dist > c2Dist
return (int)(c1Dist - c2Dist);
// end of compare()
// equals() is inherited from Object superclass
// end of DistComp class
see DistComp.java
Comparing Circles in Two Ways
Circle c1 = new Circle(0, 0, 5);
Circle c2 = new Circle(3, 2, 7);
// (x,y),r
RadiiComp rComp = new RadiiComp();
if (rComp.compare(c1, c2) < 0)
System.out.println("Circle 1 is smaller
than circle 2");
DistComp dComp = new DistComp();
if (dComp.compare(c1, c2) < 0)
System.out.println("Circle 1 is nearer to origin
than circle 2");
Circle 1 is smaller than circle 2
Circle 1 is nearer to origin than circle 2
see UseCircles.java
Sorting Circles
// sort(Object [] a, Comparator c)
Circle[] circles = // ... add circle objects;
see UseCircles.java
Arrays.sort(circles, new RadiiComp());
// circles will be sorted by ascending radii
Arrays.sort(circles, new DistComp());
// circles will be sorted by ascending distance from origin
Contest Algorithms: 2. Java Features
28
Array.binarySearch()
static int binarySearch(Object [] a, Object key)
static int binarySearch(Object [] a, Object key, Comparator c)
 Only usable on a sorted array
 If there are multiple equal elements, there is no
guarantee which one will be found
 Returns:
 Index if found the key
 (-(insertion point) - 1) if key not found
Examples
int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int index = Arrays.binarySearch(values, 8);
// find '8'
System.out.println("Index = " + index);
System.out.println("Value = " + values[index]);
 Output
Index = 7
Value = 8
Contest Algorithms: 2. Java Features
30
int[] values = { 0, 2, 4, 8 };
int index = Arrays.binarySearch(values, 400);
System.out.println(index);
// no such value
 Output
-5
// -4 -1
Contest Algorithms: 2. Java Features
31
Search for a Circle
see UseCircles.java
Circle[] circles = // ... add circle objects
Arrays.sort(circles, new DistComp());
// must be sorted before search
Circle c = new Circle(0, 0, 3);
// (x,y),r
int idx = Arrays.binarySearch(circles, c, new DistComp());
// will try to find a circle that is same distance from origin as c
Contest Algorithms: 2. Java Features
32
The Comparable Interface
 The Comparable<T> interface is another way to
compare objects.
 The interface defines a single method:
public interface Comparable<T>
{ int compareTo(T item); }
compareTo() Meaning
 compareTo() should return an integer that is negative, 0,
or positive.
 Meaning:
 obj.compareTo(item) < 0
 obj.compareTo(item) == 0
 obj.compareTo(item) > 0
when obj < item
when obj == item
when obj > item
Time24 Class with Comparable
public class Time24 implements Comparable<Time24>
{ . . .
public int compareTo(Time24 item)
//compares times
{ int time = hour*60 + minute;
// use minutes
int ttime = item.hour*60 + item.minute;
see Time24.java
// compare, returning -1, 0, or 1
if (time < ttime)
return -1;
Time24 t1 = new Time24(12,30);
else if (time == ttime)
Time24 t2 = new Time24(15,10);
return 0;
int res = t1.compareTo(t2); // -1
else
return 1;
}
}
Comparator vs. Comparable
• Comparator.compare(T x, T y)
 comparison is done between two objects, x and y
 the method is implemented outside the T class
• Comparable.compareTo(T y)
 comparison is done between 'this' object and object y
 the method is implemented by the T class
Benefits of Comparator
The
comparison code is in a separate place from the
other code for a class.
1.
This means that the same objects can be compared
in different ways by defining different Comparators
 see the two comparators for circles
3. Strings
String message = new String("Welcome to Java");
String message = "Welcome to Java";
38
Escape Characters
 How can you make a String that has quotes?
 String foo = "oh so cool";
 String bar = "oh so \"cool\", more so";
 Escape character is \ (the backslash)
39

String Comparisons
String s1 = new String("Welcome");
String s2 = "welcome";
if (s1.equals(s2))
Almost always, this
is the method you
want.
// s1 and s2 have the same contents
if (s1 == s2
// s1 and s2 have the same reference
40
 compareTo(Object object)
String s1 = new String("Welcome");
String s2 = "welcome";
if (s1.compareTo(s2) > 0)
// s1 is greater than s2
else if (s1.compareTo(s2) == 0)
// s1 and s2 have the same contents
else
// s1 is less than s2
41
Retrieving Individual Chars in a String
 Do not use message[0]
 Use message.charAt(index)
 Index starts from 0
Indices
0
1
2
3
4
5
6
message
W
e
l
c
o
m
e
message.charAt(0)
7
8
9
t
o
message.length() is 15
10 11 12 13 14
J
a
v
a
message.charAt(14)
42
Extracting Substrings
String s1 = "Welcome to Java";
String s2 = s1.substring(0, 11) + "HTML";
Indices
0
1
2
3
4
5
6
message
W
e
l
c
o
m
e
7
8
9
t
o
message.substring(0, 11)
10 11 12 13 14
J
a
v
a
message.substring(11)
43
Converting, Replacing
"Welcome".toLowerCase() returns a new string, welcome
"Welcome".toUpperCase() returns a new string, WELCOME
" Welcome ".trim() returns a new string, Welcome
"Welcome".replace('e', 'A') returns a new string, WAlcomA
"Welcome".replaceFirst("e", "AB") returns a new string, WABlcome
"Welcome".replace("e", "AB") returns a new string, WABlcomAB
"Welcome".replace("el", "AB") returns a new string, WABlcome
44
Splitting a String
String[] tokens = "Java#HTML#Perl".split("#", 0);
for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i] + "
");
displays
Java
HTML
Perl
45
Finding a Char or a Substring
"Welcome to Java".indexOf('W') returns 0.
"Welcome to Java".indexOf('x') returns -1.
"Welcome to Java".indexOf('o', 5) returns 9.
"Welcome to Java".indexOf("come") returns 3.
"Welcome to Java".indexOf("Java", 5) returns 11.
"Welcome to Java".indexOf("java", 5) returns -1.
"Welcome to Java".lastIndexOf('a') returns 14.
46
Converting into a String
There are several valueOf() methods for converting a character,
an array of characters, and numeric values into a string.
e.g.
String.valueOf(5.44)

"5.44"
47
Base Conversion (toString(n,radix))
public static void main(String[] args)
{ if (args.length != 2) {
System.out.println("Usage: java BaseChange <integer> <base>");
return;
}
int num = parseInt(args[0]);
see BaseChange.java
int base = parseInt(args[1]);
if (base < 2) {
System.out.println("Base cannot be < 2; using 16");
base = 16;
}
else if (base > Character.MAX_RADIX){
System.out.println("Base cannot be > " +
Character.MAX_RADIX + "; using 16");
base = 16;
}
String baseVal = Integer.toString(num, base).toUpperCase();
System.out.println("Conversion of " + num + " to base " +
base + " == " + baseVal);
// end of main()
Contest Algorithms: 2. }
Java Features
48
Execution
Contest Algorithms: 2. Java Features
49
The Character Class
java.lang.Character
+Character(value: char)
Constructs a character object with char value
+charValue(): char
Returns the char value from this object
+compareTo(anotherCharacter: Character): int
Compares this character with another
+equals(anotherCharacter: Character): boolean Returns true if this character equals to another
+isDigit(ch: char): boolean
Returns true if the specified character is a digit
+isLetter(ch: char): boolean
Returns true if the specified character is a letter
+isLetterOrDigit(ch: char): boolean
Returns true if the character is a letter or a digit
+isLowerCase(ch: char): boolean
Returns true if the character is a lowercase letter
+isUpperCase(ch: char): boolean
Returns true if the character is an uppercase letter
+toLowerCase(ch: char): char
Returns the lowercase of the specified character
+toUpperCase(ch: char): char
Returns the uppercase of the specified character
50
StringBuilder and StringBuffer
 StringBuilder/StringBuffer can be used wherever a
string is used
 they are faster than String if you are doing a lot of string
building
StringBuilder sb = new StringBuilder("hello");
sb.add(" andrew");
sb.add(" davison");
 after the end of the building, convert to a String:
String s = sb.toString();
51
see StringFun.java
Useful String Utilities
String reverse(String s)
String[] reverse(String[] strs)
String[] getWords(String s)
String reverseWords(String s)
String rotRight(String s)
String rotLeft(String s)
boolean isRotation(String s1, String s2)
boolean isPalindrome(String s)
String shift(String s, int shift)
char shift(char ch, int shift)
boolean isLetter(char ch)
ArrayList<String> permutate(String s)
boolean areAnagrams(String s1, String s2)
String[] genSubsets(String s)
int levDist(String s, String t)
String join(String toJoin, Object[] list
String join(String toJoin, List<String> list)
String join(String toJoin, Set set)
Contest Algorithms: 2. Java Features
boolean isNullOrEmpty(String s)
String toString(Exception e)
String unquote(String s)
String sort(String s)
String removeAll(String s, char unwanted)
String padRight(String s, int n)
String padLeft(String s, int n)
String getHexString(byte[] b)
boolean onlyDigits(String s)
boolean hasNDigits(String s, int n)
boolean isBinary(String s)
String stripControls(String s)
String removeSpaceDups(String s)
void appendToFile(String fnm, String s)
String readAll(String fnm)
ArrayList<String> toList(String[] arr)
boolean contains(String[] arr, String s)
String[] toArray(ArrayList<String> strsList)
HashSet<String> toSet(String[] arr)
52
Usage
see StringFunTests.java
public static void main(String[] args)
{
String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
String res = StringFun.reverse(s);
System.out.println("Reverse: " + res);
s = "Could you pretty please reverse this sentence";
res = StringFun.reverseWords(s);
System.out.println("Reverse Words: " + res );
String[] results = StringFun.getWords("Could you, if possible, help me!");
System.out.println("Words:");
for(String r : results)
System.out.println(" " + r);
:
Contest Algorithms: 2. Java Features
53
s = "superman";
System.out.println("Rotate right: " + StringFun.rotRight(s) );
System.out.println("Rotate left: " + StringFun.rotLeft(s) );
System.out.println("Is Palindrome: " +
StringFun.isPalindrome("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
System.out.println("Is Palindrome: " +
StringFun.isPalindrome("ABCDEFGHIJKKJIHGFEDCBA"));
results = StringFun.genSubsets("abcde");
System.out.println("Generate Subsets: {" +
StringFun.join(", ", results) + "}");
int dist = StringFun.levDist("kitten", "sitting");
System.out.println("Edit Distance: " + dist); // 3
System.out.println("Rot4: " + StringFun.shift("andrew",4));
ArrayList<String> perms = StringFun.permutate("jim");
System.out.println("Permutations: {" + StringFun.join(", ", perms) + "}");
:
Contest Algorithms: 2. Java Features
54
System.out.println("Remove all: " + StringFun.removeAll("algorithms", 'a'));
System.out.println("Pad right: \"" + StringFun.padRight("cat", 10) + "\"");
System.out.println("Is 5 digits: " + StringFun.hasNDigits("19745", 5));
String htxt = StringFun.readAll("hull1.txt");
System.out.println("Read all: \"" + htxt + "\"");
htxt = StringFun.stripControls(htxt);
System.out.println("Read all: \"" + htxt + "\"");
htxt = StringFun.removeSpaceDups(htxt);
System.out.println("Read all: \"" + htxt + "\"");
} // end of main()
Contest Algorithms: 2. Java Features
55
Contest Algorithms: 2. Java Features
56
4. Regular Expressions
 A regular expression (regex) is a pattern for matching
against a string.
 You can use regular expressions for matching,
replacing, and splitting strings.
57
Replacing and Splitting Strings
java.lang.String
+matches(regex: String): boolean
Returns true if this string matches the pattern.
+replaceAll(regex: String, replacement: Returns a new string that replaces all matching
String): String
substrings with the replacement.
+replaceFirst(regex: String,
Returns a new string that replaces the first matching
replacement: String): String
substring with the replacement.
+split(regex: String): String[]
Returns an array of strings consisting of the
substrings split by the matches.
58
Examples
boolean b = "Java is fun".matches("Java.*");
String s = "Java Java Java".replaceAll("v\\w", "wi");
String s = "Java Java Java".replaceFirst("v\\w", "wi");
String[] s = "Java1HTML2Perl".split("\\d");
Regex Documentation
 See the Pattern class documentation
 e.g. at https://docs.oracle.com/javase/8/docs/api/
java/util/regex/Pattern.html
Contest Algorithms: 2. Java Features
60
Regular Expression
x
.
(ab|cd)
[abc]
[^abc]
Matches
Example
a specified character x
any single character
a, b, or c
a, b, or c
any character except
a, b, or c
a through z
any character except
a through z
a through e or
m through p
intersection of a-e
with c-p
Java matches Java
Java matches J..a
ten matches t(en|im]
Java matches Ja[uvwx]a
Java matches Ja[^ars]a
\d
\D
\w
\W
\s
\S
a
a
a
a
a
a
Java2 matches "Java[\\d]"
$Java matches "[\\D][\\D]ava"
Java matches "[\\w]ava"
$Java matches "[\\W][\\w]ava"
"Java 2" matches "Java\\s2"
Java matches "[\\S]ava"
p*
zero or more
occurrences of pattern p
one or more
occurrences of pattern p
zero or one
occurrence of pattern p
exactly n
occurrences of pattern p
at least n
occurrences of pattern p
between n and m
occurrences (inclusive)
[a-z]
[^a-z]
[a-e[m-p]]
[a-e&&[c-p]]
p+
p?
p{n}
p{n,}
p{n,m}
digit, same as [1-9]
non-digit
word character
non-word character
whitespace character
non-whitespace char
Java matches [A-M]av[a-d]
Java matches Jav[^b-d]
Java matches
[A-G[I-M]]av[a-d]
Java matches
[A-P&&[I-M]]av[a-d]
Java matches "[\\w]*"
Java matches "[\\w]+"
Java matches "[\\w]?Java"
Java matches "[\\w]?ava"
Java matches "[\\w]{4}"
Java matches "[\\w]{3,}"
Java matches "[\\w]{1,9}"
61
Code
see RegexTest.java
import java.util.regex.*;
public class RegexTest
{
public static void main(String args[])
{
String pattern = "[a-z]+";
String text = "Now is the time";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
while (m.find())
System.out.println( text.substring(
m.start(), m.end() ) );
}
}
Output:
ow
is
the
time
Test Rig
public class TestRegex
{
see TestRegex.java
public static void main(String[] args)
{ if (args.length != 2) {
System.out.println("Usage: java TestRegex string regExp");
System.exit(0);
}
System.out.println("Input: \"" + args[0] + "\"");
System.out.println("Regular expression: \"" + args[1] + "\"");
Pattern p = Pattern.compile(args[1]);
Matcher m = p.matcher(args[0]);
while (m.find())
System.out.println("Match \"" + m.group() + "\" at positions "+
m.start() + "-" + (m.end()-1));
} // end of main()
} // end of TestRegex class
 m.group() returns the string matched by the pattern
 usually used instead of String.substring()
More Information on Regexs
 The Java tutorial on REs is very good:
 http://java.sun.com/docs/books/tutorial/
essential/regex/
 Online tutorials:
 http://ocpsoft.com/opensource/
guide-to-regular-expressions-in-java-part-1/
 and part-2
5. Bitwise Operations
 "~" inverts a bit pattern
 "<<" shifts a bit pattern to the left
 ">>" shifts a bit pattern to the right
 ">>>" shifts a zero into the leftmost pos, while the pos after ">>" depends
on sign extension
 & performs AND
 ^ performs OR
 |performs inclusive OR
Contest Algorithms: 2. Java Features
67
A Word About Bit Order
 The most-significant-bit is on the left:
10010110
^
^
|
|------- bit 0
|
|-------------- bit 7
 The value of bit 0 is 20, bit 1 is 21, ..., bit 7 is 27
Contest Algorithms: 2. Java Features
68
Code
c = a ^ b;
/* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
see BitsTest.java
c = ~a;
/* -61 = 1100 0011 */
System.out.println("~a = " + c );
public class BitsTest
{
public static void main(String args[]) {
int a = 60;
/* 60 = 0011 1100 */
int b = 13;
/* 13 = 0000 1101 */
int c = 0;
c = a << 2;
/* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );
c = a >> 2;
/* 15 = 1111 */
System.out.println("a >> 2 = " + c );
c = a & b;
/* 12 = 0000 1100 */
System.out.println("a & b = " + c );
}
c = a | b;
/* 61 = 0011 1101 */
System.out.println("a | b = " + c );
a & b = 12
a | b = 61
Contest Algorithms
c = a >>> 2;
/* 15 = 0000 1111 */
System.out.println("a >>> 2 = " + c );
// end of main()
}
a ^ b = 49
~a = -61
a << 2 = 240
a >> 15
a >>> 15
69
Bitwise Operations
Bitwise AND (&)
Bitwise inclusive OR(|)
Bitwise exclusive OR(^)
Contest Algorithms
71
Bitwise Assignment Ops
Contest Algorithms
72
Using ParseInt
 Work with binary numbers using Integer.parseInt()
 e.g. Integer.parseInt("101", 2);
 creates an integer with the binary value of 101 (decimal 5).
 Loop with binary:
// loops from 5 up to and including 15
for (int b = Integer.parseInt("0101",2);
b <= Integer.parseInt("1111",2); b++) {
/* do stuff here */
}
Contest Algorithms
73
More Information on Bits
BitFun.java
 Low Level Bit Hacks You Absolutely Must Know
 http://www.catonmat.net/blog/low-level-bit-hacks-you-absolutelymust-know/
 10 hacks, including: " Check if the integer is even or odd", "Test if the n-th bit is
set", "Set the n-th bit", "Unset the n-th bit", toggle the nth bit
 Bit Twiddling Hacks
 https://graphics.stanford.edu/~seander/bithacks.html
 Hacker's Delight, 2nd ed
Henry S. Warren
 http://www.hackersdelight.org/
Contest Algorithms
74