面试题算法实现(一)

1.在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b

public static char GetFirstChar(string str)
        {
            char result = ' ';
            for (int i = 0; i < str.Length; i++)
            {
                int num = 0;
                for (int j = 0; j < str.Length; j++)
                {
                    if (str[i].Equals(str[j]))
                    {
                        num++;
                    }
                }
                if (num == 1)
                {
                    result = str[i];
                    break;
                }
            }
            return result;
        }

2.输入一个已经按升序排序过的数组和一个数字,在数组中查找两个数,使得它们的和正好是输入的那个数字。
如果有多对数字的和等于输入的数字,输出任意一对即可。例如输入数组12471115和数字15。由于4+11=15,因此输出411

 public static void GetTheRightValue(int[] arr, int a)
        {
            List<int> list = new List<int>();
            for (int i = 0; i < arr.Length; i++)
            {
                for (int j = i + 1; j < arr.Length; j++)
                {
                    if ((arr[i] + arr[j]) == a)
                    {
                        list.Add(arr[i]);
                        list.Add(arr[j]);
                    }
                }
            }
            for (int i = 0; i < list.Count; i++)
            {
                Console.Write(list[i].ToString() + " ");
                if (i % 2 != 0)
                {
                    Console.WriteLine();
                }
            }
        }

3.1+2++n
要求不能使用乘除法、forwhileifelseswitchcase等关键字以及条件判断语句(A?B:C)。

public static int add(int n) {
            int s = n;
            if (n != 0) {
                s +=add(n - 1);
            }           
            return s;
        }




4.输入一个整数n,求从1nn个整数的十进制表示中1出现的次数。

例如输入12,从112这些整数中包含1 的数字有11011121一共出现了5次。

//下面代码是100以内的数字的处理

 public static int GetTheNumber(int n) {
            int num = 0;
            int s = n / 10;
            int s1 = n % 10;
            if (s >= 2 && s1 >= 1)
            {
                num = 12 + s - 1;
            }
            else if (s >= 2 && s1 <1)
            {
                num = 12 + s - 2;
            }
            else if (s == 1 && s1 >= 1)
            {
                num = s1 + 3;
            }
            else if (s == 1 && s1 < 1)
            {
                num = 2;
            }
            else {
                num = 1;
            }                 
            return num;       
        }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值