2014-11-05 112 views
0

我想比較兩個整數的數字來判斷它們是否有不同的數字。 我在我的hasDistinctIntegers方法上遇到了麻煩。它不經常評估它應該如何。如果該號碼沒有重複數字,則爲真,如果是,則爲false。我相信我的其他方法工作正常,但我真的可以使用另一套眼睛!這是我到目前爲止:比較整數的數字

public static void main(String[] args) { 

    System.out.println(hasDistinctDigits(12345)); 
} 

public static boolean hasDistinctDigits(int number) { 
    boolean returner = true; 
    int count1 = 0; 
    int digit = 0; 
    int curNum = number; 
    while (count1 < numDigits(number)) { 
     int count2 = 0; 
     digit = getDigit(curNum, count1); 
     curNum = curNum/10; 
     while (count2 < numDigits(curNum)) { 
      if (digit == getDigit(curNum, count2)) { 
       returner = false; 
      } 
      count2++; 
     } 
     count1++; 

    } 

    return returner; 
} 

public static int numDigits(int number) { 
    int count = 0; 
    while (number != 0) { 
     number /= 10; 
     count++; 
    } 
    return count; 
} 

public static int getDigit(int number, int i) { 
    int digit = 0; 
    int count = 0; 
    int originalNum = number; 

    while (count <= i) { 
     if (count == i) { 
      digit = number % 10; 
     } 
     number /= 10; 
     count++; 
    } 
    if (i > numDigits(originalNum)) { 
     return -1; 
    } else { 
     return digit; 
    } 
} 

public static int indexOf(int number, int digit) { 
    int count = 0; 
    int index = -1; 
    while (count < numDigits(number)) { 
     if (getDigit(number, count) == digit) { 
      index = count; 
     } 
     count++; 
    } 
    return index; 
} 

在此先感謝您的任何提示/建議!

回答

2

使用Set<Integer>可以作爲這樣的代碼如下:

public static boolean hasDistinctDigits(int number) 
{ 
    final Set<Integer> set = new HashSet<Integer>(); 

    while (number > 0) { 
     if (!set.add(number % 10)) 
      return false; 
     number /= 10; 
    } 

    return true; 
} 

你也可以使用一個普通數組:

public static boolean hasDistinctDigits(int number) 
{ 
    // We rely on Java's default values here: 
    // uninitialized ints will be set to 0. 
    final int[] digits = new int[10]; 
    // But for peace of mind, we can... 
    Arrays.fill(digits, 0); 

    int digit; 

    while (number > 0) { 
     digit = number % 10; 
     if (digits[digit]++ > 0) 
      return false; 
     number /= 10; 
    } 

    return true; 
} 

請注意,上述兩種方法不檢查他們的說法是否是大於0.


使用Java 8,您甚至可以獲得更多樂趣:

public static boolean hasDistinctDigits(int number) 
{ 
    final Set<Integer> set = new HashSet<>(); 
    return String.valueOf(number).chars().allMatch(set::add); 
} 

但在這個層面上,這是智力手淫,真的...(或(INT)Stream濫用 - 你挑)