题目很简单,完成函数reverse,要求实现把给定的一个整数取其相反数的功能,举两个例子如下:
- x = 123, return 321
- x = -123, return -321
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 按位取反
{
class Program
{
static void Main(string[] args)
{
int n = -121231243;
Console.WriteLine(0-Rerver(n));
Console.Read();
}
static int Rerver(int n)
{
//n = 0 - n;
int m;
int res = 0;
int len = GetLength(n);
//进入循环之前保留下长度
int length = GetLength(n);
int i = 0;
while (true)
{
i++;
len--;
//去摸获取数据从后往前取
m = n % 10;
//重新生成n
n = (n - m)/10;
//构造结果
int digit = 1;
for (int k = 0; k < len; k++)
{
digit = digit * 10;
}
res += digit * m;
if (i == length)
{
break;
}
}
return res;
}
static int GetLength(int n)
{
int len = 0;
while (true)
{
len++;
n = n / 10;
//只有个位数才会为0
if (n == 0)
{
break;
}
}
return len;
}
}
}