TechArena Community Integer length problem

#1
13-11-2009
 Member Join Date: Nov 2009 Posts: 359
Integer length problem

Hi everyone
I have a problem in my code, I think this is a simple problem but it's not clicking. I searched for this problem but I could not find the problem. Suppose, consider integer x = 987456, I want to write a program to find the length of integer without using any in-built functions in the library (obviously in this case the result should be 6). Remember it it is an array then its simple. But its an integer datatype. Any help on this. I still think this is a simple problem, so I am expecting a help from you.
#2
13-11-2009
 Member Join Date: May 2008 Posts: 2,383
Re: Integer length problem

Hello,
ya this is a simple program, but no worry's it happens sometimes with every one. Check out the following code.
Code:
```int p=12345;
int count = 0;
while(p !=0 )
{
p= p/10; //removes the last digit of the number; or better p /= 10
count++;
}```
Now, after the loop is executed "p" will be zero count will count the number of digits in the number. If you want back "p" just use int b=p; // this should be before the loop or p=b; //this should be after the loop.
__________________
The FIFA Manager 2009 PC Game
#3
13-11-2009
 Member Join Date: Jan 2008 Posts: 1,515
Re: Integer length problem

The above program is correct. But still to increase you knowledge I have posted a simple code, just go through it.
Code:
```int a=12345;
if(a<0)a=-a;
int count = 0;
int remainder, reverse=0; // ----change over here
while(a !=0 )
{
remainder = a%10; // to read the last digit -----change
a = a/10; //removes the last digit of the number; or better a /= 10
reverse = (reverse * 10) + remainder; //this statement should come before count++ else the value will be 543210
count++;
}```
If you have any more problems in future do post back again. Your problem will be definitely solved.

 Tags: