你怎么能得到一个int(C#)的第一位?
问题描述:
在C#中,什么是要得到一个int第1位的最佳方式?我想出的方法是把INT转换成字符串,找到字符串的第1字符,然后将其重新为int。
In C#, what's the best way to get the 1st digit in an int? The method I came up with is to turn the int into a string, find the 1st char of the string, then turn it back to an int.
int start = Convert.ToInt32(curr.ToString().Substring(0, 1));
虽然这做工作,感觉就像有可能是一个很好的,简单的,基于数学的解决这样的问题。字符串操作感觉沉闷。
While this does the job, it feels like there is probably a good, simple, math-based solution to such a problem. String manipulation feels clunky.
编辑:不论速度的差异,MyString的[0],而不是子串()仍然只是字符串操作
irrespective of speed differences, mystring[0] instead of Substring() is still just string manipulation
答
下面是如何
int i = Math.Abs(386792);
while(i >= 10)
i /= 10;
和 I
将包含你所需要的。