重复除法模运算:
long num = 123456789;
int count = 0;
while(num > 0)
{
int digit = num % 10;
if(digit == 1)
count ++;
num /= 10;
}将其转换为String,并在该位置获取字符:
long num = 123456789;
int count = 0;
String s = String.valueOf(num);
for(int i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
if(ch == '1')
count ++;
}第二个运算不需要每次得到余数和商。一个charAt()方法就足够了。
哪种方法被认为更好,为什么?
考虑从控制台获取输入。
第一宗案件:
long num = scanner.nextLong();第二宗案件:
String s = scanner.nextLine();这里没有将number转换为string的开销。
也让我们假设这是正数。
发布于 2015-07-23 09:38:22
我建议第三种方法扩展到字符串的转换方法:向List of Character的转换。
这样做的好处是您可以使用Java 8集合流特性对元素执行筛选、聚合和其他功能。
例如,您的示例可以这样表示(在@h.j.k的注释后面编辑):
long num = 123456789;
String s = String.valueOf(num);
long count = s.chars()
.mapToObj(i -> (char)i)
.filter(ch -> ch.equals('1'))
.count();发布于 2018-01-31 18:47:57
下面的方法允许您根据特定的索引从int值中获取特定的数字。
public static int getSpecificNum(int number, int index) {
int numOfDigits = 0;
int pow = 1, test = 0, counter = 0;//获取数字数
while (test != number) {// once the full int is retrieved
counter++;//<-digit counter
pow *= 10;
test = number % pow;//go through the entire int
}//位数被找到,重置所有
numOfDigits = counter;
counter = 0;
pow = 1;
test = 0;//现在计数直到索引
while (counter != (numOfDigits - index)) {// this is numOfDigits was needed
counter++;
pow *= 10;
test = number % pow;// same thing
}// exp =求10的幂
int exp = numOfDigits - (index + 1);
exp = (int) Math.pow(10, exp);
return test / exp;//divide and conquer
}发布于 2019-04-10 00:56:40
如果要查找数字的长度,则不需要数组。只需使用log 10就可以得到这个数字有多少个位置,
long num = 123456789;
int length = (int) Math.log10(num); //should make the length 9现在要得到一个特定的号码
public int getNthDigit(int number, int base, int n) {
return (int) ((number / Math.pow(base, n - 1)) % base);
}如果您输入getNthDigit(num,10,8);,那么它将返回2。
https://codereview.stackexchange.com/questions/97770
复制相似问题