我有一个数组,由一个英文字母a到z组成,除了一个字母。我不知道缺少哪个元素,我只需要使用一个循环就可以找到该元素。我不能使用if语句和内置函数。
真的有可能吗?我在考试中遇到了这个问题,找不到任何解决方案,它的确使我吃不消。任何见解都很感激。
// missing 'h'
var letters = ['a','b','c','d','e','f','g','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
for (var i = 0; i < letters.length; i++) {
// find missing letter in 1 loop with no if statements or built-in functions
}
答案 0 :(得分:3)
这是代码:
char[] inputs = { 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
int total = 0;
foreach (char c in inputs)
{
total += (int)c - (int)'a';
}
char missingChar = (char)((int)('a') + (325 - total));
// version 2
total = 0;
//from sum of a arithmetic sequence for even number of values
// for example 1 + 2 + 3 + 4 = (1 + 4) + (2 + 3) = 2 * 5 = 10
int expectedTotal = 13 * ((int)'a' + (int)'z');
foreach (char c in inputs)
{
total += (int)c;
}
missingChar = (char)((expectedTotal - total));
答案 1 :(得分:0)
class Program
{
private static void FindLetter(string[] alphabet, string[] yourMissingLetter)
{
for (var i = 0; i < yourMissingLetter.Length; i++)
{
var isit = alphabet[i] == yourMissingLetter[i];
Console.WriteLine("alphabet[{0}] = {1}", alphabet[i], isit);
}
}
static void Main(string[] args)
{
string[] alphabet = { "A", "B", "C", "D" };
// let's say your array is missing B
string[] yourMissingLetterArray = { "A", "C", "D" };
FindLetter(alphabet, yourMissingLetterArray);
}
}
不如实际答案那么妙,但这将起作用:
当它开始丢失字母的那一刻,它将变为假,索引将向您显示它是哪个字母。
答案 2 :(得分:0)
这是不使用任何循环而仅列出函数(控制台应用程序)的另一种方法,它还解决了小写比较问题:
namespace MissingAlphbetLetters
{
class Program
{
public static List<char> CheckDifferences(char[] str)
{
List<char> alphabet= new List<char>(new char[]
{ 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'});
List<char> compaired = str.ToList().ConvertAll(l => char.ToLower(l));
List<char> difference = new List<char>();
if (str.Length > 0)
{
difference = alphabet.Except(compaired).ToList();
}
return difference;
}
static void Main(string[] args)
{
Console.Write(string.Join(",",CheckDifferences(new char[] { 'A', 'g', 't', 'h', 'o', 'm', 'd', 'e' })));
Console.ReadLine();
}
}
}