Expression puzzles, expressions
I. Judge odd numbers
When it comes to determining odd numbers, the first response is I % 2 = 1; however, this is a big problem;
The statement of negative number is incorrect !! BecauseNegative % 2 =-1
So it can be improvedI % 2! = 0;
It can also be further optimized. As we all know, bit operations are extremely fast, so there are:I & 1! = 0; => optimal solution !!!
Ii. Change Time
Change:2-1.1 =?
Direct output: System. out. println (2-1.1); ==>0.8999999999999999
This is because not all decimal places in the computer can be exactly expressed in binary,
BigDecimal can be used for exact representation, and must be usedBigDecimal (String)
Improvement: printf can be used for output !!
System. out. printf ("%. 2f", 2-1.1 );
Optimization: Using BigDecimal:
System. out. println (new BigDecimal ("2.00"). subtract (new BigDecimal ("1.10 ")));
3. Long division
Long/long
The number of milliseconds in a day/The number of microseconds in a day
final long weimiao = 24 * 60 * 60 * 1000 * 1000;final long haomiao = 24 * 60 * 60 * 1000; System.out.println(weimiao / haomiao); //5
This is caused by weimiao overflow. Although the computation results do not overflowIn the calculation process, it is calculated as int type., Weimiao generates overflow, causing an error in the result !!!
The solution is simple. Replace the int constant with a long constant as the factor of every product:
1 final long weimiao = 24L * 60 * 60 * 1000 * 1000;2 final long haomiao = 24L * 60 * 60 * 1000;3 4 System.out.println(weimiao / haomiao); //1000
The result is correct !!
When operating a large number, always pay attention to the overflow problem. If you are not sure, use long for calculation !!
Iv. hexadecimal
System. out. println (Long. toHexString (0x00000000l + 0 xcafebabe); ==> cafebabe
! If the highest bit of the hexadecimal or octal literal constant is set, it is a negative number !!!!
Where long + int ==> is automatically converted to long + long
In addition, the second number symbol extension:
You can program the second number to the long type to avoid destructive symbol extension !!
System. out. println (Long. toHexString (0x00000000l + 0 xcafebabeL); ==> 1 cafebabe