CSDN論壇上看到的面試題,將連續更新

題目:

1、給定兩個字符串str1和str2。要求判斷STR2能否被通過循環移位所得到的字符串所包含。如,給定str1=ABCDD,str2=DDAB,返回true。給定Str1=ABCDE,str2=DDAB,返回false.

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine(Check("ABCDE", "DDAB"));
            Console.ReadKey();
        }

        private static bool Check(string str1, string str2)
        {
            int index = -1;
            foreach (char c in str2.ToCharArray())
            {
                index = str1.IndexOf(c);
                if (index != -1)
                {
                    str1 = str1.Remove(index);
                    index = -1;
                }
                else
                    return false;
            }
            return true;
        }
    }
}


2、五隻猴子分桃。半夜,第一隻猴子先起來,它把桃分成了相等的五堆,多出一隻。於是,它吃掉了一個,拿走了一堆; 第二隻猴子起來一看,只有四堆桃。於是把四堆合在一起,分成相等的五堆,又多出一個。於是,它也吃掉了一個,拿走了一堆;......其他幾隻猴子也都是 這樣分的。問:這堆桃至少有多少個?

下面看看最直接的算法

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int input = 0;
            while (input < 10000)
            {
                if (Check(input))
                {
                    Console.WriteLine(input);
                }
                input++;
            }
            Console.ReadKey();
        }

        private static bool Check(int input)
        {
            if (input % 5 != 1)
                return false;

            int temp1 = (input - 1) * 4 / 5;
            if (temp1 % 5 != 1)
                return false;

            int temp2 = (temp1 - 1) * 4 / 5;
            if (temp2 % 5 != 1)
                return false;

            int temp3 = (temp2 - 1) * 4 / 5;
            if (temp3 % 5 != 1)
                return false;

            int temp4 = (temp3 - 1) * 4 / 5;
            if (temp4 % 5 != 1)
                return false;
            return true;
        }
    }
}


發佈了41 篇原創文章 · 獲贊 7 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章