Làm thế nào để chuyển đổi giá trị của hai số bằng toán tử bit XOR trong C-Sharp? (How to swap the contents of two numbers using bitwise XOR operation in C-Sharp?)

Đây là một bài khá hay, bạn sẽ học hỏi và hiểu rõ hơn về toán tử bit XOR trong C-Sharp, và đây cũng là một lời giải khác cho bài tập chuyển đổi hai số mà không sử dụng biến thứ ba mà ta thường gặp khi học cơ bản về ngôn ngữ lập trình C#.



C-Sharp Basic Example:
---------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpExample
{
    class swap_the_contents_of_two_numbers
    {

        static void Main(string[] args)
        {

            int i, k;

            Console.WriteLine("Enter two integers \n");
            i = int.Parse(Console.ReadLine());
            k = int.Parse(Console.ReadLine());

            Console.WriteLine("\n Before swapping i= {0} and k = {1}", i, k);
            i = i ^ k;
            k = i ^ k;
            i = i ^ k;

            Console.WriteLine("\n After swapping i= {0} and k = {1}", i, k);
            Console.ReadLine();

        }

    }
}
---------------------------------











No comments:

Post a Comment