PDA

View Full Version : extracting digits from a large integer...



legacy-britton
07-22-2003, 11:08 AM
Hey,
Let's say I've got a 3 digit integer, say 321, and I want to isolate each digit into its own variable... so the 100's digit would become say Var100, 10's would become Var10, and 1's becomes Var1.
So, I'd run this integer through some little function and ideally end up with:

Var100 = 3
Var10 = 2
Var1 = 1

Does anybody have any ideas how I could actually do this? I'm sure it's not too difficult, but I'm not really the most creative programmer. I know there are other ways to go about this, but it'd require a pretty major rewrite of exisiting code to compensate....
Thanks!

legacy-britton
07-22-2003, 11:36 AM
well, 30 seconds after posting this I figured out one way... I'd sorta forgotten about Do Until statements...
check it:



Var100 = 0;
var10 = 0;
var1 = 0;

Do{ Value = Value - 100;
Var100 = Var100 + 1; }
Until (Value < 100) ;

Do{ Value = Value - 10;
Var10 = Var10 + 1; }
Until (Value < 10) ;

Var1 = Value;


This does the trick, but seems awfully inefficient...

elmuerte
07-22-2003, 04:57 PM
var100 = value / 100;
value = value % 100;
var10 = value / 10;
var1 = value % 10;

legacy-Mr Evil
07-22-2003, 05:24 PM
Originally posted by El_Muerte_[TDS]


var100 = value / 100;
value = value % 100;
var10 = value / 10;
var1 = value % 10;

Won't rounding-up cause that to go wrong? e.g., if value==399, you get var100==4, var10==10, var1==10.

legacy-Doc_EDo
07-22-2003, 05:58 PM
OR

local int var100; //must use INT
local int var10;
local int var1;

//local int digits;
local int tmpVar;

tmpVar = digits;

var100 = tmpVar/100;
tmpVar -= var100 *100;

var10 = tmpVar/10;
tmpVar -=var10 *10;

var1 = tmpVar;

elmuerte
07-23-2003, 03:33 AM
Originally posted by Mr Evil
Won't rounding-up cause that to go wrong? e.g., if value==399, you get var100==4, var10==10, var1==10.

good question, but it shouldn't
you are doing an integer division not a float division and cast to int (shouldn't matter tho)

note: as Doc_EDO said, types have to be int or else it'll fail

legacy-britton
07-23-2003, 09:33 AM
Hey guys,
yeah, the types are definitely integers, probably should've mentioned that...
I had originally considered just doing simple division but figured I would have problems with things rounding like Mr Evil was worried about... Sure enough, it seems to work though!
Thanks guys!