Chương trình viết trên VS2013, Project C# -> Windows Console Application...
-----------------------------CODE-------------------------------using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace LTMHTT
{
class Program
{
static void Main(string[] args)
{
int x, y;
Console.WriteLine("Nhap x: ");
x = Int32.Parse(Console.ReadLine());
Console.WriteLine("Nhap y: ");
y = Int32.Parse(Console.ReadLine());
int[] b = new int[30];
int l=0;
Console.WriteLine("So {0} la: ", x);
nhiPhan(x, b,ref l);
xuatKQ(b, l);
Console.ReadKey();
int[] w = new int[30];
Console.WriteLine("Ket qua {0} + {1} la: ", x, y);
congSoNguyen(x, y,ref w,ref l);
xuatKQ(w, l);
Console.ReadKey();
Console.WriteLine("Ket qua {0} - {1} la: ", x, y);
truSoNguyen(x, y, ref w, ref l);
xuatKQ(w, l);
Console.ReadKey();
}
static void nhiPhan(int x,int[] a,ref int l)
{
int n=0;
while (Math.Pow(2, n) <= x)
{
n++;
}
int nplus = n + 1;
int i=0;
int k = 0;
for (i=n;i>=1;i--){
if (Math.Pow(2, i) <= x)
{
k = 1;
}
else
{
k = 0;
}
a[i] = k;
x = x - k * (int)(Math.Pow(2, i));
};
a[0]=x;
int r=a[0];
l = n;
//for (int j = n; j >= 0; j--) Console.Write(a[j]);
}
static void xuatKQ(int[] k,int l)
{
for (int j = l; j >= 0; j--) Console.Write(k[j]);
Console.WriteLine("\n--------------------");
}
static void congSoNguyen(int x, int y, ref int[] w, ref int l)
{
int l1 = 0; int l2 = 0;
int[] p = new int[30];
int[] q = new int[30];
nhiPhan(x, p, ref l1);
nhiPhan(y, q, ref l2);
//Phan chinh
int c = 0;
int n;
if (l1 > l2) n = l1; else n = l2;
for (int i = 0; i <= n; i++)
{
int t = p[i] + q[i] + c;
w[i] = t % 2;
if (t < 2) c = 0; else c = 1;
}
w[n + 1] = c;
l = n + 1;
}
static void truSoNguyen(int x, int y, ref int[] w, ref int l)
{
int l1 = 0; int l2 = 0;
int[] p = new int[30];
int[] q = new int[30];
nhiPhan(x, p, ref l1);
nhiPhan(y, q, ref l2);
//Phan chinh
int c = 0;
int n;
if (l1 > l2) n = l1; else n = l2;
for (int i = 0; i <= n; i++)
{
int t = p[i] - q[i] + c;
w[i] = Math.Abs(t % 2); // Vi 17-9 = "-1000" ???
if (t < 0) c = -1; else c = 0;
}
}
}
}
-----------------------------/CODE-------------------------------Tác giả: Nguyễn Bằng