Câu hỏi phỏng vấn Golang
Câu hỏi

How do you swap two values? Provide a few examples.

Câu trả lời

Swapping two values refers to the process of exchanging the values of two variables. There are several methods to achieve this in programming, and the approach can vary depending on the programming language and specific requirements. Here are a few examples of how to swap two values:

Using a Temporary Variable

The most common and straightforward method to swap two values is by using a temporary variable. This method is language-agnostic and can be used in almost any programming language.

c Copy
int a = 10, b = 20, temp;
temp = a; // Store the value of 'a' in 'temp'
a = b;    // Assign the value of 'b' to 'a'
b = temp; // Assign the value of 'temp' (original 'a') to 'b'

Arithmetic Operations

Another method to swap two values is by using arithmetic operations such as addition and subtraction without using a temporary variable. However, this method is limited to numeric values and can lead to overflow issues with large integers or loss of precision with floating-point numbers.

c Copy
int a = 10, b = 20;
a = a + b; // 'a' becomes 30
b = a - b; // 'b' becomes 10 (original value of 'a')
a = a - b; // 'a' becomes 20 (original value of 'b')

Bitwise XOR Operation

The XOR bitwise operation can also be used to swap two values without a temporary variable. This method works with integer values and leverages the properties of XOR.

c Copy
int a = 10, b = 20;
a = a ^ b; // 'a' now contains the result of XOR between 'a' and 'b'
b = a ^ b; // 'b' is now the original value of 'a'
a = a ^ b; // 'a' is now the original value of 'b'

Parallel Assignment

Some programming languages, such as Python, support parallel assignment, which allows for a concise way to swap values.

python Copy
a = 10
b = 20
a, b = b, a # 'a' becomes 20 and 'b' becomes 10

Multiplication and Division

Similar to the arithmetic method, multiplication and division can be used, but this approach is not recommended due to the possibility of division by z...

middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What is the difference between C.sleep() and time.Sleep() ?

entry

What is Go?

senior

What is an idiomatic way of representing enums in Go?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào