Thema: Delphi Get number digits

Einzelnen Beitrag anzeigen

Benutzerbild von Aphton
Aphton

Registriert seit: 31. Mai 2009
1.198 Beiträge
 
Turbo Delphi für Win32
 
#8

AW: Get number digits

  Alt 12. Dez 2013, 18:41
Here are the mathematical fucntions you need:

digitCount(x) := ⌈log10(x+1)⌉
extractDigit(x, digitIdx) := ⌊x / 10^(digitCount(x)-digitIdx)⌋ mod 10

(sidenote - "⌈⌉" stands for ceiling, "⌊⌋" for flooring)

Example number = 1234
digitCount(1234) = ⌈log10(1234+1)⌉
= ⌈3.09⌉
= 4

extractDigit(1234, 2) = ⌊1234 / 10^(4 - 2)⌋ mod 10
= ⌊1234 / 10^2⌋ mod 10
= ⌊1234 / 100⌋ mod 10
= ⌊12.34⌋ mod 10
= 12 mod 10
= 2

Edit: This is mathematically as low as it gets.. Cant think of a shorter way right now.
Bitshifting works on base 2. You would have to remap which is an extra overhead that is not needed.
There are assembler instructions (SSE, SSE2, ..) that are faster.
As far as I know the math.pas functions use the optimized assembler operations. Use it!
das Erkennen beginnt, wenn der Erkennende vom zu Erkennenden Abstand nimmt
MfG

Geändert von Aphton (12. Dez 2013 um 19:09 Uhr)
  Mit Zitat antworten Zitat