YTU OJ 3489 C#异或运算符的使用

YTU OJ 3489 C#异或运算符的使用

在这里插入图片描述
看到题目很多人都会想直接使用

int num = Convert.ToInt32(Console.WriteLine)

读取输入的数;但是事情往往没有这么简单,直接使用 Convert.ToInt32()没有考虑到如果输入的是String类型就会转换失败并抛出异常:System.FormatException:“Input string was not in a correct format.”

这时候我们就需要用到int.TryParse()方法来检测转换是否可以进行转换,然后再用异或运算符

a=a^b;
b=a^b;
a=a^b;

调换a和b的位置;然后就可以通过了;
在这里插入图片描述

using System;
class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        int i=0;
        int c, d;
        String a = Console.ReadLine();
        String b = Console.ReadLine();
        if (int.TryParse(a, out i))
        {
    
    
            c = Convert.ToInt32(a);
        }
        else
            c = 0;
        if (int.TryParse(b, out i))
        {
    
    
            d = Convert.ToInt32(b);
        }
        else
            d = 0;
        Console.WriteLine("before exchange first={0},second={1}",c,d);
        c = c ^ d;
        d = c ^ d;
        c = c ^ d;
        Console.WriteLine("after exchange first={0},second={1}",c,d);
    }
}

TryParse用法
在这里插入图片描述
看完有帮助点个赞吧。

猜你喜欢

转载自blog.csdn.net/henishu/article/details/114647158