C#の古典的なアルゴリズムのインタビューの質問

1.再帰的アルゴリズムを使用して、1 + 2 + 3 + 4 +…+ 100の結果を計算します

static int SUM(int x)
{
    
    
  if (x <= 1)
    return x;
	else
    return x + SUM(x - 1);
}

2.バブルソートアルゴリズムを実装します(昇順)

static void Sort(int[] nums)
{
    
    
    int temp;
    for (int i = 0; i < nums.Length; i++)
    {
    
    
        for (int j = i + 1; j < nums.Length; j++)
        {
    
    
            if (nums[i] > nums[j])
            {
    
    
                temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
            }
        }
        Console.WriteLine(nums[i]);
    }
}

3.任意の入力文字列の各文字の出現回数をカウントするメソッドを実装します

/** 字典的定义
 必须包含名空间System.Collection.Generic
 Dictionary里面的每一个元素都是一个键值对(由二个元素组成:键和值)
 键必须是唯一的,而值不需要唯一的
 键和值都可以是任何类型(比如:string, int, 自定义类型,等等)
 通过一个键读取一个值的时间是接近O(1)
 键值对之间的偏序可以不定义
*/
static void CountChar(string str)
{
    
    
    Dictionary<char, int> dic = new Dictionary<char, int>();
    foreach (char c in str)
    {
    
    
        if (dic.ContainsKey(c))
            dic[c]++;
        else
            dic.Add(c, 1);
    }
    foreach (KeyValuePair<char, int> p in dic)
    {
    
    
        Console.WriteLine("字符{0},出现的次数{1}", p.Key.ToString(), p.Value.ToString());
    }
}

4.文字列を整数に変換するメソッドを実装します。int.Parse、int.TryParse、Convert.ToInt32などのライブラリメソッドは使用しないでください。

static bool TryParse(string s, out int num)
{
    
    
    if (!string.IsNullOrWhiteSpace(s))
    {
    
    
        num = 0;
        return false;
    }
    int result = 0;

    bool minus = s[0] == '-' ? true : false;
    if (minus && s.Length == 1)
    {
    
    
        num = 0;
        return false;
    }

    for (int i = minus ? 1 : 0; i < s.Length; i++)
    {
    
    
        if (s[i] >= '0' && s[i] <= '9')
        {
    
    
            result = s[i] - 48 + result * 10;
        }
        else
        {
    
    
            num = 0;
            return false;
        }
    }

    num = minus ? -result : result;
    return true;
}

5.数字の列のルールは次のとおりです:1、1、2、3、5、8、13、21、34 ... 30桁目は何ですか、再帰的アルゴリズムを使用して

static int Foo(int i)
{
    
    
    if (i <= 0)
        return 0;
    else if (i > 0 && i <= 2)
        return 1;
    else
        return Foo(i - 1) + Foo(i - 2);
}

おすすめ

転載: blog.csdn.net/qq_43562262/article/details/110634559
おすすめ