How to get the last digit of a number

匿名 (未验证) 提交于 2019-12-03 02:23:02

问题:

How to get the last digit of a number. e.g. if 1232123, 3 will be the result

Some efficient logic i want so that it is easy for results having big numbers. After the final number i get, i need to some processing in it.

Thanks a lot

回答1:

Just take mod 10:

Int32 lastNumber = num % 10; 


回答2:

It's just the number modulo 10. For example in C

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


回答3:

Here's the brute force way that sacrifices efficiency for obviousness:

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


回答4:

 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";             } 


回答5:

Another way is..

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


回答6:

The best would be:

Math.Abs(num % 10); 

Cause num % 10 will give you negative result for negative numbers



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!