Java tricks & knowledge Summary

1. Get number of digits in an int

var length = (int)Math.Floor(Math.Log10(n) + 1);

2. Keyword Super

Use super to refer superclass method if the method has been override in the subclass.

super.overrideMethod();

3. Random Integer Number

generate random number range 1 to 100

(int)(Math.random() * 101);

4. Int --> String

  • String number = Integer.toString(int i); 
  • String number = String.valueOf(int i);

4.1 Array --> String

Arrays.toString(arr);

5. String --> Int

  • int x = Integer.parseInt("9");

6. Integer.MAX_VALUE & MIN

  -2^31 to 2^31-1  --->  -2147483648 to 2147483647

7. Decimal to Octal

  String octal = Integer.toOctalString(decimal);  ----or----

 1 public static String decimal2Octal(int n) {
 2     String s = "";
 3     int rem;
 4     char[] dig = {'0', '1', '2', '3', '4', '5', '6', '7'};
 5     
 6     while(n > 0) {
 7         rem = n % 8;
 8         s = dig[rem] + s;
 9         n = n/8;
10     }
11     return s;
12 }

 

8. Greatest Common Divisor

public static int GCD(int a, int b) {
    if(b == 0)    return a;
    return GCD(b, a%b);
}

 

  

posted on 2014-11-16 11:33  SuperBo  阅读(168)  评论(0编辑  收藏  举报