Skip to content

Instantly share code, notes, and snippets.

public static void drawHorizontalLine(byte[] screen, int width, int x1, int x2, int y) {
int height = screen.length / width;
if (y < 0 || y >= height || x1 < 0 || x1 >= screen.length * 8 || x2 < 0 || x2 >= screen.length * 8)
return;
int base = y * width / 8;
int start = base + x1 / 8;
int end = base + x2 / 8;
byte mask1;
if (x1 % 8 == 0)
public int swapBits(int num) {
return (num & 0x55555555) << 1 | (num & 0xAAAAAAAA) >> 1;
}
public int bitNumber(int a, int b) {
int n = a ^ b;
int cnt = 0;
while (n > 0) {
if ((n & 1) == 1)
cnt++;
n >>= 1;
}
return cnt;
}
public static String toBinary(double num) {
if (num >= 1 || num < 0) {
return "ERROR";
}
StringBuffer sb = new StringBuffer();
sb.append("0.");
int i;
for (i = 0; i < 32 && num != 0; i++) {
if (num >= 0.5) {
sb.append(1);
public static int insertMtoN(int N, int M, int i, int j) {
int mask = (~(1 << (j - i + 1) - 1)) << i;
return (N & mask) | (M << i);
}
public void allPaths(TreeNode root, int target) {
if (root == null)
return;
int dep = depth(root);
int[] path = new int[dep];
findPaths(root, target, 0, path);
}
private void findPaths(TreeNode root, int target, int level, int[] path) {
if (root == null)
public boolean isSubtree(TreeNode t1, TreeNode t2) {
if (t2 == null)
return true;
if (t1 == null)
return false;
if (isMatch(t1, t2))
return true;
return isSubtree(t1.left, t2) || isSubtree(t1.right, t2);
}
public TreeNode LCA(TreeNode root, TreeNode p, TreeNode q) {
if (root == null)
return null;
if (!isExisted(root, p) || !isExisted(root, q))
return null;
return LCA_helper(root, p, q);
}
private boolean isExisted(TreeNode root, TreeNode node) {
if (root == null)
public TreeNode getNext(TreeNode node) {
if (node.right != null)
return getMin(node.right);
TreeNode parent = node.parent;
while (parent != null && parent.right == node) {
node = parent;
parent = node.parent;
}
return parent;
}
public boolean isBST(TreeNode root) {
return isBST_helper(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private boolean isBST_helper(TreeNode root, int minValue, int maxValue) {
if (root == null)
return true;
return root.val > minValue && root.val < maxValue
&& isBST_helper(root.left, minValue, root.val)
&& isBST_helper(root.right, root.val, maxValue);