查找数字的单个数字

时间:2015-12-17 22:25:58

标签: java string substring

在java中,我想检查一个数字的每个数字是奇数还是偶数。例如,如果你要运行代码,你会得到 -

13451: 4 odd 1 even
5555 : 4 odd
18529: 3 odd 2 even

从我所看到的,您可以将数字转换为字符串,并将其子串。然后,在这之后,你可以检查它是否是奇数。

但是怎么样?

代码(以及更多解释)

public class numberSorter
{
    public static void main(String[] args){
        for(int i = 0;i<100000;i++){
        //So here I want it so that I can see which numbers from 1-100000
        //have all odd number digits.Using a for loop makes it easier,
        //but how would you do it with "i"?
        }
    }
}

4 个答案:

答案 0 :(得分:1)

好吧,如果你只是对只有奇数位的数字感到好奇,你不一定要计算奇数和偶数的数字。如果你需要通过计算它们来解决这个问题,那么正确答案将是具有0偶数位的数字。为此,您可以在本主题中看到许多答案。如果没有,我建议你在循环中使用这个简单的函数:

//This function checks if a specific number has only odd digits
private static boolean isHasAllDigitsOdd(int number)
{
    //first of all check if the number is 0
    if(number==0)
    {
        return false;
    }

    //while the last digit is odd cut that form the number
    while((number>0)&&(number%2==1))
    {
        number /= 10;
    }

    //if the number is 0 then all of its digits were cut
    if(number ==0)
    {
        return true;
    }
    else//otherwise it has a even digit
    {
        return false;
    }
}

因此在定义函数后,您的循环将如下所示:

public static void main(String[] args){
    for(int i = 0;i<100000;i++){
        if(isHasAllDigitsOdd(i))
        {
            System.out.println(i);
        }
    }
}

答案 1 :(得分:0)

@Test
public void testEvenOdd(){
    for(int i = 0;i<100000;i++){
        int even = 0; 
        int odd  = 0; 

        String number = Integer.toString(i);
        for (int index = 0; index < number.length();index++){
            int num = number.charAt(index); 
            if (even(num)){
                even++;
            }
            else{
                odd++;
            }
        }
        System.out.println(i+" " + even + " even " + odd + " odd");
        }
}

public boolean even(int number){
    if (number%2==0){
        return true;
    }
    else{
        return false;
    }
}

答案 2 :(得分:0)

有很多方法可以解决这个问题。这是使用while循环的一个:

int startingNum = num;
int evenCount = num == 0 ? 1 : 0; // handles the 0 input
int oddCount = 0;
while (num > 0) {
    if (num % 2 == 0)
        evenCount++;
    else
        oddCount++;
    num /= 10;
}
System.out.println(startingNum + " : " + oddCount + " odd " + evenCount + " even");

答案 3 :(得分:0)

public static void main(String[] args){
    long number = 12354689;
    long dividor = (long) Math.pow(10,String.valueOf(number).length()-1);
    int oddNum = 0;
    int evenNum = 0;

    while(dividor >= 1){
        if(((int) number/dividor) % 2 == 0)
            evenNum = evenNum + 1;
        else
            oddNum = oddNum + 1;
        dividor = dividor/10;
    }
    System.out.println("Even Number = " + evenNum);
    System.out.println("Odd Number = " + oddNum);


}