c#十进制转二进制算法 和字符串反转算法


去某软面试 面试官给个题上黑板做,写个算法 求95转2进制后1的个数。

我在黑板上敲了

static int count = 0;
        /// <summary>
        /// 获取10进制数转2进制后中1的个数
        /// </summary>
        public static void BinCount(int a)
        {
            int n = -1;
            int b = 0;
            while(b<=a)
            {
                n++;
                b = (int)Math.Pow(2, n);
            }
            count++;
            var m = (int)Math.Pow(2, n - 1);
            if (a - m <= 0)
            {
                return;
            }
            BinCount(a - m);
        }

  下面是main函数调用  返回的结果是6 完全正确。

static void Main(string[] args)
        {
            BinCount(95);
            var binCount= count;
        }

 其实面试官是考你怎么把10进制转成2进制 要求写出10进制转2进制的算法

于是乎我又写了如下:

        static string str =string.Empty;
        /// <summary>
        /// 10进制转2进制
        /// </summary>
        /// <param name="a"></param>
        public static void GetBinary(int a)
        {
            if(a % 2 == 0)
            {
                str += "0";
            }
            else
            {
                str += "1";
            }
            if(a / 2<1)
            {
                return;
            }
            GetBinary(a / 2);
        }  

应该用

StringBuilder 只有一个指针 不然空间会浪费很多

下面是main 函数调用 结果是 1111101

static void Main(string[] args)
        {

            GetBinary(95);
            var binarya = str;
        }

  好吧 结果 是反的,那再考你一个 字符串反转。给你个 “abcd”  给我返回“dcba”

我又写了下面反转方法:

/// <summary>
        /// char数组反转
        /// </summary>
        /// <param name="str"></param>
        public static void Reverse(char[] str)
        {
            if (str == null)
            {
                return;//空判断这个细节一定不能漏
            }
            int i = 0;
            while(i<str.Length-1-i)
            {
                var tem = str[i];
                str[i] = str[str.Length -1- i];
                str[str.Length -1- i] = tem;
                i++;
            }
        }

  于是乎 二进制的也就完整了  返回的binary =1011111

static void Main(string[] args)
        {

            GetBinary(95);
            var binary = str;
            char[] arr = str.ToCharArray();
            Reverse(arr);
            binary = new string(arr);
        }

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM