2017-04-11 53 views
-3

如果我有478523698作爲一個整數,如何找到第二個最低的數字只有條件沒有將其轉換爲字符串,這個問題在採訪中被問到。我通過轉換整型數組這樣從整數查找第二個最低的數字,而不使用c#中的任何數組和函數?

`

int integer=478523698; 
    //converting integer to array 
     string s,numbers = integer.ToString(); 
     char[] num = numbers.ToCharArray(); 
     int L=num.Length; 
     int[] intArray = new int[L]; 
     for (int i = 0; i <L; i++) 
     { 
      s = num[i].ToString(); 
      intArray[i] = Convert.ToInt32(s); 
     } 

    //code for getting 2nd lowest number 
    int min1=intArray[0]; 
    int min2=0; 
    if (min2 < min1) 
     { 
      min1 = intArray[1]; 
      min2 = intArray[0]; 
     } 
    for(var i=0;i<=intArray.Length-1;i++){ 
      if (intArray[i] < min1) 
      { 
       min2 = min1; 
       min1 = intArray[i]; 
      } 
      else if (intArray[i] < min2) 
      { 
       min2 = intArray[i]; 
      } 

    } 
    Console.Write("Second Lowest Number is {0} ",min2); ` 
+0

你嘗試過什麼?第二低的數字是多少? – CurseStacker

+0

我用一個'for循環'做了這個,我得到了答案,但他想要這個,如果條件 –

+0

可以顯示你的'for'循環嗎? – CurseStacker

回答

4

我認爲你可以做到這一點,無須轉換爲字符串得到的輸出,並用一個簡單的循環和條件如下所示:

int inputInteger = 478523698; 
int numberSample = inputInteger; 
int lowest = int.MaxValue, secondlowest = int.MaxValue; 
while (numberSample != 0) 
{ 
    int digit = numberSample % 10; 
    numberSample = numberSample/10; 
    if (digit < secondlowest && digit!=lowest) 
    { 
     secondlowest = digit; 
    } 
    if (secondlowest < lowest) 
    {     
     int temp = secondlowest; 
     secondlowest = lowest; 
     lowest = temp; 
    } 
} 
if (secondlowest == int.MaxValue) 
{ 
    Console.WriteLine("There is no second lowest number"); 
} 
else 
{ 
    Console.WriteLine("Lowest digit in {0} is {1} and second lowest digit is {2}", inputInteger,lowest,secondlowest); 
} 

Working example,您可以看到上面的代碼將打印輸出爲Lowest digit in 478523698 is 2 and second lowest digit is 3,如果初始化inputInteger222表示輸出將是There is no second lowest number

+0

感謝它的工作 –

0

我敢肯定,這可以簡化,但它的工作原理...

class Program 
{ 
    static void Main(string[] args) 
    { 
     var number = 478523698; 
     var numberList = new List<int>(); 

     for (var i = 1; i <= number; i *= 10) 
     { 
      var currentNumber = number/i % 10; 
      numberList.Add(currentNumber); 
     } 

     Console.WriteLine(numberList.OrderBy(x => x).Skip(1).FirstOrDefault()); 

     Console.Read(); 
    } 
} 
+0

大聲笑,當我發佈它兩個其他答案被添加。 –

+2

不允許使用數組 –

相關問題