Hiya, I have a int x = 28492374 and need to add every other digit together and then later do other stuff with the digits like take every other digit and multiple by two then add each digit together. Anways i dont know the method call out a single digit from an int.

Recommended Answers

All 6 Replies

int temp,x=28492374,a[];
temp=x;
for(i=0;i<=7;i++)
{
a=temp%10;
temp=temp/10;
}

You should know the classes and their methods:

java.lang.Integer
java.lang.String

for example:
java.lang.String st = java.lang.Integer.toString(x);

a single digit from an int

It depends on the number's base. You use the modulus and divide operators to get at the "digits" of the int number. For base 10 use % 10 and / 10
Remember all data is stored in the computer in binary.
We humans like decimal and use base 10 representations to talk about "digits". But an int can be represented in any base. Other common ones are hex and octal.

Just a code to sum up all the digits of a number

int n = 232323, sum = 0, d;
while(n!=0)
{
d = n%10;
sum = sum + 10;
n = n/10;
}

its a very basic method to extract digits from a number provided the base of the number is 10.

provided the base of the number is 10.

Why the limitation to only base 10. I think you can do it in any base.
The sum of 123 in base 4 would be 6 base 10 or 12 base 4.

u can do it for any base
all u have to do is jst change 10 to the required base ....
its not a limitations....
i have given a code for base 10

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.