返回整数的第一个数字 [英] Return first digit of an integer

查看:240
本文介绍了返回整数的第一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中返回整数的第一个数字。?

How in Java do you return the first digit of an integer.?

即。

345

返回3的int。

推荐答案

最简单的方式是使用 String.valueOf(Math.abs((long)x))。charAt(0 ) - 这将给你一个 char 1 。要将其作为整数值,你可以减去'0'(如在Unicode中,'0'到'9'是连续的)。

The easiest way would be to use String.valueOf(Math.abs((long)x)).charAt(0) - that will give it you as a char1. To get that as an integer value, you could just subtract '0' (as in Unicode, '0' to '9' are contiguous).

这有点浪费,当然。另一种方法是取绝对值,然后循环除以10,直到数字在0-9范围内。如果这是作业,那就是我给出的答案。但是,我不会为它提供代码,因为我认为可能是作业。但是,如果您提供意见并编辑您的答案以解释您正在做的以及您遇到的问题,我们可能会提供帮助。

It's somewhat wasteful, of course. An alternative would just be to take the absolute value, then loop round dividing by 10 until the number is in the range 0-9. If this is homework, that's the answer I'd give. However, I'm not going to provide the code for it because I think it might be homework. However, if you provide comments and edit your answer to explain how you're doing and what problems you're running into, we may be able to help.

1 需要注意的一点是, Integer.MIN_VALUE 的绝对值不能表示为一个 int - 所以你可能应该首先转换为 long ,然后使用 Math.abs 然后做算术。这就是为什么那里有演员。

1One sticky point to note is that the absolute value of Integer.MIN_VALUE can't be represented as an int - so you may should first convert to a long, then use Math.abs, then do arithmetic. That's why there's a cast there.

这篇关于返回整数的第一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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