获取int中位数的方法? [英] Way to get number of digits in an int?

查看:39
本文介绍了获取int中位数的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有比这种方法更简洁的方法来获取 int 中的位数?

Is there a neater way for getting the number of digits in an int than this method?

int numDigits = String.valueOf(1000).length();

推荐答案

你的基于字符串的解决方案完全没问题,没有什么不整洁"的地方.你必须意识到,从数学上讲,数字没有长度,也没有数字.长度和数字都是特定基数(即字符串)物理表示的属性.

Your String-based solution is perfectly OK, there is nothing "un-neat" about it. You have to realize that mathematically, numbers don't have a length, nor do they have digits. Length and digits are both properties of a physical representation of a number in a specific base, i.e. a String.

基于对数的解决方案执行(某些)与基于字符串的解决方案在内部所做的相同的事情,并且可能(微不足道)更快地执行此操作,因为它只产生长度而忽略数字.但实际上我不会认为它的意图更清晰 - 这是最重要的因素.

A logarithm-based solution does (some of) the same things the String-based one does internally, and probably does so (insignificantly) faster because it only produces the length and ignores the digits. But I wouldn't actually consider it clearer in intent - and that's the most important factor.

这篇关于获取int中位数的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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