Number of digits and which digits it is in integer
Example int i=185;
Then I w开发者_StackOverflow中文版ant to get that 'i' contains 3 digits and those digits are 1,8, and 5.
Hint: You need to take the modulus of the number by 10, to get the last digit. And then divide the same number by 10, do get the first two numbers. Repeat yourself as many times as required.
1st solution:
/**
* Using Integer/String classes functionality
*/
public class Shweta {
private static Integer i = 185;
public static void main(String... args) {
String iStr = i.toString();
for (char digit : iStr.toCharArray()) {
System.out.println(digit);
}
System.out.println("Length is: " + iStr.length());
}
}
2nd solution:
/**
* Doing that in a 'homework' way
*/
public class ShwetaNoCheats {
private static Integer i = 185;
public static void main(String... args) {
int length = 0;
while (i != 0) {
System.out.println(i - (i / 10) * 10);
i /= 10;
length++;
}
System.out.println("Length is: " + length);
}
}
The easy way to do this is by converting to a locale-agnostic string, then looking at each character in the string. I am not giving the final solution in case this is homework, but here are some important APIs...
Converting to string:
String stringForm = Integer.toString(number);
Handling negatives:
int nonNegative = Math.abs(number);
Length of a string:
int length = stringForm.length();
Getting the i-th character of a string:
char c = stringForm.charAt(i);
One way would be:
int i = 185;
int a = i / 100; // 1
int b = (i % 100) / 10; // 8
int c = i % 10; // 5
But i think you need something more generic? Try via string
int i = 185;
String iAsString = String.format("%d", i);
if(iAsString.contains("1")){
// do something...
}
And more advanced:
int i = 185;
String iAsString = String.format("%d", i);
HashSet<Integer> set = new HashSet<Integer>();
for(char c : iAsString.toCharArray()){
set.add(Integer.valueOf(String.valueOf(c)));
}
Then you can work on the set.
The number of decimal digits is also given by Math.ceil(Math.log10(i)), for integral i
.
精彩评论