2013-03-31 17 views
16

Come ottenere l'ultima cifra di un numero. ad es. se 1232123, 3 sarà il risultatoCome ottenere l'ultima cifra di un numero

Un po 'di logica efficiente voglio che sia facile ottenere risultati con numeri grandi. Dopo il numero finale che ottengo, ho bisogno di un po 'di elaborazione in esso.

Grazie mille

+1

provare una divisione modulo, dividendo per 10 (operatore%) –

+0

il resto della divisione modulo del 10 è l'ultima cifra :) –

risposta

35

Basta prendere mod 10:

Int32 lastNumber = num % 10; 
+0

Questo è un residuo, non un quoziente. –

+0

il termine non è diviso penso che la risposta sia giusta .... – Dani

11

E 'solo il numero di modulo 10. Ad esempio in C

int i = 1232123; 
int lastdigit = (i % 10); 
5

Ecco il modo forza bruta che sacrifica l'efficienza per ovvietà:

int n = 1232123; 
int last = Convert.ToInt32(n.ToString() 
          .AsEnumerable() 
          .Last() 
          .ToString()); 
+0

lol, sapevo che questo sarebbe stato downvoted, e ci sono voluti tutti 1ms per accadere :) –

+0

Non è molto ovvio sia ... – MrKWatkins

+0

ovvio rispetto a che cosa? modding di 10? –

2
The best way to do this is -> int lastNumber = (your number) % 10; 
And if you want to return the last digit as string you can do this switch 

      (number % 10) 
      { 
       case 0: 
        return "zero"; 
       case 1: 
        return "one"; 
       case 2: 
        return "two"; 
       case 3: 
        return "three"; 
       case 4: 
        return "four"; 
       case 5: 
        return "fife"; 
       case 6: 
        return "six"; 
       case 7: 
        return "seven"; 
       case 8: 
        return "eight"; 
       case 9: 
        return "nine"; 
      } 
1

altro modo è ..

var digit = Convert.ToString(1234); 
var lastDigit = digit.Substring(digit.Length - 1); 
Problemi correlati