Algorithm
This week's LeetCode titled 371. Sum of two integers
Here are two integers a
and b
, Don't use Operator +
and -
, Calculates and returns the sum of two integers .
Input :a = 1, b = 2
Output :3
According to the four cases of adding two binary bits, they are as follows :
0 + 0 = 0
0 + 1 = 1
1 + 0 = 1
1 + 1 = 0 ( carry )
Without considering carry , nothing The result of carry addition is a^b
; Whether to carry or not depends on a&b
, Therefore, the result of carry is (a&b)<<1
. therefore , We can put integers a and b And , Split into a and b The sum of the non carry addition result and the carry result . Because each split can shift the lowest bit to the left by at least one bit , Again because a and b You can take a negative number . Because signed integers are represented by complements , therefore 0 And negative numbers also apply to the above methods .
class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
}
Review
This week, Review The English article is : Best practices for writing code comments
Too many code comments do not guarantee their quality , Good comments should help others understand the code more easily , Here are some suggestions on how to ensure code quality :
- Comments should not duplicate code .
Bad examples
i = i + 1; // Add one to i
A more extreme example of error
// create a for loop // <-- comment
for // start for loop
( // round bracket
// newline
int // type for declaration
i // name for declaration
= // assignment operator for declaration
0 // start value for i
- Good comments cannot be an excuse for unclear code .
Bad examples , Variable n
The meaning of is not clear
private static Node getBestChildNode(Node node) {
Node n; // best child node candidate
for (Node node: node.getChildren()) {
// update n if the current state is better
if (n == null || utility(node) > utility(n)) {
n = node;
}
}
return n;
}
A good example , The variable should be n
Renamed as bestNode
, This is enough for others to understand without comments .
private static Node getBestChildNode(Node node) {
Node bestNode;
for (Node currentNode: node.getChildren()) {
if (bestNode == null || utility(currentNode) > utility(bestNode)) {
bestNode = currentNode;
}
}
return bestNode;
}
If you can't write clear notes , There may be a problem with the code .Unix The most notorious comment in the source code is “You are not expected to understand this( You shouldn't understand this )”, Unfortunately , Dennis Ritchie who wrote these notes , He doesn't fully understand the code himself , Later I had to rewrite the code .
Comments should eliminate confusion , Instead of causing confusion . If your code comments cause ambiguity , Please delete it .
Explain the single code in the comments .
Bad examples , Code should not explain code that everyone can understand , Unless you're writing tutorials for novices .
final Object value = (new JSONTokener(jsonString)).nextValue();
// Note that JSONTokener.nextValue() may return
// a value equals() to null.
if (value == null || value.equals(null)) {
return null;
}
- Provide a link to the original source of the copied code . Here is a good example :
/** Converts a Drawable to Bitmap. via https://stackoverflow.com/a/46018816/2219998. */
return (int) (0.3 * red + 0.59 * green + 0.11 * blue);
- Include links to external references where they are most helpful . occasionally , You can also give a link to the manual :
// http://tools.ietf.org/html/rfc4180 suggests that CSV lines
// should be terminated by CRLF, hence the \r\n.
csvStringBuilder.append("\r\n");
- Add comments when fixing errors . Here is a good example :
// NOTE: At least in Firefox 2, if the user drags outside of the browser window,
// mouse-move (and even mouse-down) events will not be received until
// the user drags back inside the window. A workaround for this issue
// exists in the implementation for onMouseLeave().
@Override
public void onMouseMove(Widget sender, int x, int y) { .. }
- Use annotations to mark incomplete implementations . Here's an example :
// TODO(hal): We are making the decimal separator be a period,
// regardless of the locale of the phone. We need to think about
// how to allow comma as decimal separator, which will require
// updating number parsing and other places that transform numbers
// to strings, such as FormatAsDecimal
in fact , Many code comments are actually the same as shown in the figure below :
Tip
clock()
Functions and gettimeofday()
Similarities and differences of functions :
- Common ground : Both can get the current time , By calculating the difference between the current time before and after , Then get the running time of a piece of code
- Difference :
clock()
yes C Library functions , This means that it can be used in any system ; andgettimeofday()
Functions are just Linux Functions in the system , Therefore, it can only be used in Linux The system uses .
Share
Released C Language reading and writing CSV The tutorial trilogy , The reading data of each platform is significantly better than ARTS Many series , It can be seen that the platform and everyone prefer tutorials with specific points , More articles of this type will be created in the future .