你怎么能得到一个int(C#)的第一位? [英] How can you get the first digit in an int (C#)?

查看:2001
本文介绍了你怎么能得到一个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 将包含你所需要的。

这篇关于你怎么能得到一个int(C#)的第一位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆