How to calculate the digits of a positive integer? Comment calculer les chiffres d'un entier positif?
I just came across the need to calculate the digits of a number. It sounds trivial as we can see the digits & count them easily. Je viens de tombé sur la nécessité de calculer les chiffres d'un nombre. Il semble trivial que nous pouvons voir les chiffres et les compter facilement.
The challenge is how to find them (with least effort) computationally? Le défi est de savoir comment les trouver (avec moins d'effort) de calcul?
Solution:
1 + (int) (Math.log(i) / base10) 1 + (int) (Math.log (i) / base10)
where base10 = Math.log(10) où base10 = Math.log (10)
Filed under Classé sous Java Software Logiciel de Java | |
| |
RSS 2.0 RSS 2,0 | |
Email this Article Envoyer cet article
You may also like to read Vous mai également à lire |





January 25th, 2004 at 6:16 am Janvier 25, 2004 at 6:16 am
Hmm. Did a search and found this. Aller à une recherche et trouvé. http://mindprod.com/jgloss/widthindigits.html
If you are strictly dealing with ints, it seems like this method is the most optimized as it doesn’t require any method calls or logorithmic computation. Si vous êtes strictement traitant de ints, il semble que cette méthode est la plus optimisée car elle ne nécessite pas de méthode d'appels ou de logorithmic calcul. It performs at most 3 simple comparisons. Il effectue tout au plus 3 comparaisons simples.
/** / **
* Counts number decimal digits in a 32 bit signed number. * Numéro de compte chiffres décimaux en 32 bits un nombre signé. 0 => 1, 9 => 1, 0 => 1, 9 => 1,
* 99 => 2, 2,147,483,647 => 10 * 99 => 2, 2.147.483.647 => 10
*
* @param x * @ Param x
* number whose digits you wish to count. * Nombre dont les chiffres que vous souhaitez à compter. Must lie in range 0 .. Doit se situer dans la gamme 0 ..
* Integer.MAX_VALUE; * Integer.MAX_VALUE;
*
* @return number of digits in x, eg Integer.toString(x).length() * @ Return nombre de chiffres en x, par exemple Integer.toString (x). Length ()
* @author Marc Chappuis * @ Author Marc Chappuis marnic@ludomedia.ch
*/ * /
public static int widthInDigits(int x) { public static int widthInDigits (int x) (
// do an unravelled binary search / / Faire un dégradée binaires de recherche
if (x if (x