Java Puzzle -1__java

Source: Internet
Author: User
Tags arithmetic integer division

Do not think the domestic translation many classic books are mixed up, I see this Java puzzle good. There is an English download on the Internet, and a Taiwanese Mr. Chua seems to have translated the traditional Java FAQ. I decided to use a simple Chinese grammar to translate, so that beginners can understand what I am talking java. If you see my mistake in translating the children, be sure to let me know. Because I am not very understand ha. Email:goddie2046@gmail.com

There are many chapters in this book, take it slow.

English Original:

-------------------------------------------- Puzzle 1:oddity

The following method purports to determine whether it sole argument is a odd number. Does the method work?

public static Boolean isodd (int i) {return

    i% 2 = 1;

}


Solution 1:oddity

An odd number can being defined as an integer this is divisible by 2 with a remainder of 1. The expression I% 2 computes the remainder when I was divided by 2 and so it would seem. Unfortunately, it doesn ' t; It returns the wrong answer one quarter of the time.

Why one quarter? Because half of all int values are negative, and the IsOdd method fails to all negative values. It returns False when invoked to any negative value, whether even or odd.

This is a consequence of the definition of Java ' s remainder operator (%). It is defined to satisfy the following identity of all int values A and all nonzero int values B:

(A/a) * b + (a% b) = = A


In the other words, if you are divide a by B, multiply the result by B, and add the remainder, your are back where you started [JLS 15.17.3]. This identity makes perfect sense, but at combination with Java ' s truncating integer division operator [JLS 15. 17.2], it implies that then the remainder operation returns a nonzero result, it has the same sign as its left operand.

The IsOdd method and the definition of the ' term odd on which it is based both assume ' all remainders are. Although this assumption makes sense for some kinds of division [Boxing], Java ' s remainder operation is perfectly matched To it integer division operation, which discards the fractional part of it result.

When I was a negative odd number, I% 2 is equal to-1 rather than 1, so the IsOdd method incorrectly false. To prevent this sort of surprise, test that your methods behave properly when passed negative, zero, and positive values F or each numerical parameter.

The problem is easy to fix. Simply Compare I% 2 to 0 rather than to 1, and reverse the sense of the comparison:

public static Boolean isodd (int i) {return

    i% 2!= 0;

}


If you are using the IsOdd method in a performance-critical setting, you would is better off using the bitwise AND Operato R (&) in place of the remainder operator:

public static Boolean isodd (int i) {return

    (I & 1)!= 0;

}


The second version may run much faster than the "the", depending on what platform and virtual machine you using, and I s unlikely to run slower. As a, the divide and remainder operations are slow compared to other arithmetic and logical. It's a bad idea to optimize prematurely, but in this case, the faster version are as clear as the original, so there is no Reason to prefer the original.

In summary, I am about the signs of the operands and of the result whenever your use the remainder operator. The behavior of this operator was obvious when its operands are nonnegative, but it isn ' t so obvious when one or both opera NDS are negative.

-------------------------

Goddie translation

-----------------------------

Puzzle 1:oddity
Puzzle 1: Odd.

The following isodd (int i) method is used to determine if I is an odd number. It's useless. Please see:

public static Boolean isodd (int i) {

return I% 2 = 1;

}

Solution 1:oddity (Odd)
Solution 1: Odd numbers

An odd number is defined as an integer that is 2 apart from 1. Even the Martians know that the expression: I% 2 is used to calculate I by 2 in addition to the remainder, you would say that the above code is not very good. Not really.

, or the effect is not very good. This code has One-fourth cases to return an incorrect result.

Why is One-fourth.

Because one-second of integers are negative, one-second of integers are positive. The above isodd (int i) method does not work correctly when I is a negative number. If I is a negative number, none

Whether I is a negative odd number or a negative even number, this method returns FALSE.

The following is a decision about the Java remainder operator (%).

The remainder operator (%) is rolled back from this equation (where a is an integer and B is a non-zero integer):

(A/a) * b + (a% b) = = A

That is, the% operation satisfies this condition: if A is divided by B, the quotient times B, plus the value of a% B, the end result must be equal to a.

This formula is not only very reasonable, but it is just using the divide operator in Java.
It can also be derived from this decision: when the remainder operation gets a non 0 result C, the number A on the left of the remainder operator (%) and the result C should be the same symbol (positive or negative)

Number, or 0).

The isodd (int i) method above and the so-called "odd number" are assumed to be positive values for the remainder operation. While this assumption applies to a subset of the scenarios, the remainder in Java

The operation is perfectly consistent with her division, and the division in Java does not qualify the integer symbol.

If I in the isodd (int i) method is a negative odd number, I% 2 result should be-1 instead of 1, at which point isodd (int i) returns an incorrect result: false.

To avoid this error, you should test your code completely with various numbers (integers, negative numbers, 0) after the code is written.

The problem with this isodd (int i) method is easy to fix. Just determine if I% 2 is equal to zero.

public static Boolean isodd (int i) {

Return i% 2!= 0;

}

If you want to use the isodd (int i) method in a demanding environment, it would be better to use the "logic and" operator (&) to replace the remainder operator (%):

public static Boolean isodd (int i) {

Return (I & 1)!= 0;

}


The second version will generally run faster than the first version. As for how fast it depends on your virtual machine, it is not likely to be slower than the first edition. The general laws are: Division and residual operations

are slower than other arithmetic and logical operations (CPUs are additive.) Multiplication does not have to do too much conversion, the equivalent of several additions. )。 Always thinking that optimizing the code is not

Good, others will not understand you write the code. Our example is better, the second fast version and the first edition are easier to read, so there is no reason to use the first edition.

The final summary is not good.

1. When you use the remainder operation, remember to consider the number of operands and the symbol of the result.
2. When the number of operands is non-negative, the execution of the remainder operation code is obvious, but if some numbers are negative, the execution of the code is not so obvious.


Goddie:

Do not despise the domestic waste translation, a lot of classics have been ruined. It's a perfect translation to have fun, if you think there is fraught place please be sure to inform me: goddie2046@gmail.com

------------------------------

Complete

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.