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.

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.

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.

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.

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

entry

What is Go?

middle

Is Go an object-oriented language?

junior

What is static type declaration of a variable in Go?

Bình luận

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

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