Java(数百、数千等)
我想构建一个方法,如果输入数字为数千(例如 3458
),则输出 1000
;如果输入数字为数百,则输出 100
等等。这可能吗?
I would like to build a method that outputs 1000
if the input number is thousands (eg. 3458
), 100
if the input number is hundreds and so on. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
当然有可能。为什么不发布您尝试过的内容,我们可以为您提供如何解决任何问题的指导。
Of course it is possible. Why don't you post what you tried and we can give you pointers on how to solve any problems.
正如 Steve 所说,首先自己尝试一下,然后带着一个具体问题来回答 SO(即“我正在做 X,这是我的代码,为什么 Y 没有发生?”),这可能是一个好主意。
然而,作为一个小提示,假设您有纯数字输入(即它始终只是数字流,没有“,”等),您实际上可以仅使用字符串进行计算 - 无需工作完全具有数字类型(int等)...
(好吧,考虑一下,最后可能需要一些数学运算才能得到“100”或“1000”等的最终结果,但不多。)
As Steve said, it's probably a good idea to give it a little try yourself first, then come to SO with a specific question (i.e. "I am doing X, this is my code, why isn't Y happening?").
However, as a small hint, assuming you have pure numeric input (i.e. it will always just be a stream of numbers, with no ","s or the like) you can actually do the working out using just strings - no need for working with numerical types (int, etc) at all...
(Okay, thinking about this, there might be a little math right at the end to get the final result of '100' or '1000' etc, but not much.)
为了扩展 Yuval 提供的内容,如果您不关心数字的符号(即输入值,例如 +3456 和 -3456 都应返回 1000),您可以只使用输入的绝对值:
如果你想处理所有可能的数字输入,你也可以在计算之前处理零值:
log(0) 是未定义的,所以如果 n == 0 你不想执行计算。你'会得到一个有趣的答案(如果你甚至得到一个答案......我没有运行这段代码)。鉴于您提供的问题描述,我认为当输入为 0 时返回 0 是有意义的。零不在千位、百位、十位或个位中——在整数中,它有自己的类别。所以你可以返回 0。或者你可以抛出异常。
To expand on what Yuval offered, if you don't care about the sign of the number (that is, input values of, say, +3456 and -3456 should both return 1000), you can just use the absolute value of the input:
And if you want to handle all possible numeric inputs, you could also handle the zero-value before doing your calculation:
log(0) is undefined, so you don't want to perform the calculation if n == 0. You'll get a funny answer (if you even get an answer... I didn't run this code). Given the description of the problem you provided, I think returning 0 when the input is 0 makes sense. Zero isn't in the thousands or the hundreds or the tens or the ones -- among the integers, it is its own category. So you could return 0. Or you could throw an exception.
它并不花哨,但简单易读。
Its not fancy, but its simple and readable.
简单的数学:
Simple math:
循环可用于避免使用 double 和最终的舍入问题(如果将结果转换为
int
)。循环变量从 1 开始,每次循环乘10,而(下一个)结果小于输入数。
负和零输入需要特殊处理。
A loop can be used to avoid using double and an eventual rounding problem (if transforming the result to
int
).The loop variable starts with 1 and is multiplied by 10 each pass while the (next) result is less than the input number.
Negative and zero input need a special handling.