Java检查int的下一位是否等于当前位

时间:2018-11-26 12:47:34

标签: java int

我想确定一个int是否连续包含2个或更多相同的数字。

示例:

int value1 = 12345; // should return false
int value2 = 123451; // should return false
int value3 = 12344; // should return true

public boolean isNextDigitSame(int valueToCheck) {
    // implementation

    String number = String.valueOf(numberToTest);

    int[] numberAsArray = new int[number.length()];

    for(int i = 0; i < number.length(); i++) {

        int j = Character.digit(number.charAt(i), 10);

        numberAsArray[i] = j;

        System.out.println(j);
}

到目前为止,我已经设法将输入转换为数组,但是我不确定下一步该怎么做。

2 个答案:

答案 0 :(得分:1)

  public boolean isNextDigitSame(int valueToCheck) {
// implementation
      int previousDigit = -1;
      while(valueToCheck>0){
          int currentDigit=valueToCheck%10;
          if(currentDigit==previousDigit )
              return true ;
          previousDigit =currentDigit;
          valueToCheck/=10;  
     }
   return false;
}

答案 1 :(得分:0)

因为您已将所有数字的位存储在数组中,所以现在要做的就是检查数字是否会随着时间重复。您可以通过取每个数字并将其与其他数字进行比较来做到这一点(请勿将其与数字本身进行比较!!!)。可以通过一个简单的for-in-for循环轻松地进行比较,因为该数字是整数,所以需要O(n * n)运算(对于整数,n最多可以为10)。 这是您需要做的:

public class DigitChecker {

public boolean isNextDigitSame(int valueToCheck) {
    // implementation

    String number = String.valueOf(valueToCheck);

    int[] numberAsArray = new int[number.length()];

    for(int i = 0; i < number.length(); i++) {

        int j = Character.digit(number.charAt(i), 10);

        numberAsArray[i] = j;

        //System.out.println(j);    doesn't need to be used in this situation
    }

    for(int i = 0; i<number.length(); i++){
        int digit = numberAsArray[i]; // take each digit and compare it with the other digits
        for(int j = 0; j<number.length(); j++){
            if(digit == numberAsArray[j] && (i == j-1 || i == j+1)) // if you found the digit which equals to your 
                return true;                                        // digit and it's in a row, 
        }                                                           // just stop the program and return true
    }
    return false; // this will execute if only you didn't find any 2/more digits
}
public static void main(String[] args) {    
    int value1 = 12345; // should return false
    int value2 = 123451; // should return false
    int value3 = 12344; // should return truev
    DigitChecker checker = new DigitChecker();
    System.out.println(checker.isNextDigitSame(value1)); // false
    System.out.println(checker.isNextDigitSame(value2)); // false
    System.out.println(checker.isNextDigitSame(value3)); // true

}

}