Thread: Digits of an integer.

1. Member
Join Date
Dec 2009
Posts
20
Rep Power
0

Digits of an integer.

i have a problem given in the book but i dont know how to deal with it,

problem:
Write a program that displays all integers between low and high that are the SUM OF THE CUBE OF THEIR DIGITS, In other words, find all the numbers xyz
such as xyz = x(cube) + y (cube) + z (cube) , for example
153 = 1(cube) + 5 (cube) + 3(cube). Try 100 for low and 1000 for high.

sorry for using the word cube i dont know how to type the exponent "3" :p

anyway, i totally understand the case but i dont know how to get EACH digit of a given integer, something like the method .charAt(<location>) of the String class, thats where im stuck up. taking EACH digit one-by-one.

anyhelp would be appreciated

by the way, the next exercise after this is ,

-write a method that returns the number of digits in an integer argumet; for example 23,498 has five digits.
Last edited by Allgorythm; 12-30-2009 at 09:00 AM.

2. Member
Join Date
Dec 2009
Posts
20
Rep Power
0
this is what i've got sor far

p
Java Code:
```ublic class Sample {

public static void main(String[] args) {

int integer = 153,
sum = 0;

String convert = "" + integer;

char temp = 0;

for (int q = 0; q <= convert.length() - 1; q++) {

temp = convert.charAt(q);

sum = sum + (int) temp;
}

System.out.println(sum);
}
}```
all i can do is to make the number a string first. So i can locate each every character, then after they become characters ill cast them to integer then add them,
:confused:

3. Member
Join Date
Dec 2009
Posts
20
Rep Power
0
Java Code:
```    public static void main(String[] args) {

int integer = 153,
sum = 0;

String convert = "" + integer;
// i even tried this one String convert = "197"; but the output is 167
int temp;

for (int q = 0; q <= convert.length() - 1; q++) {

temp = (int) convert.charAt(q);

sum = sum + (int) temp;
}

System.out.println(sum);
}```
i made an implicit conversion of the integer into string, and i followed what you have said, but its still 153 :confused:
Last edited by Allgorythm; 12-30-2009 at 11:33 AM.

4. Look at the following code.

Java Code:
```        String str= "123";
int iSum = 0;

for(int index = 0; index < str.length(); index++) {

// Get the int value
int iTemp = Integer.parseInt(Character.toString(str.charAt(index)));

// Cube
iSum += iTemp * iTemp * iTemp;
}

System.out.println(iSum);```

5. Member
Join Date
Dec 2009
Posts
20
Rep Power
0
tnx for that!, that solved it, i forgot the method of Integer class...

6. Member
Join Date
Dec 2009
Posts
20
Rep Power
0
ahh so this is not the only way to do this program.....
can i ask for a little sample? if it wont bother you...

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•