Thursday, 15 August 2013

java - Comparing digits of integers -



java - Comparing digits of integers -

i trying compare digits of 2 integers tell if have distinct digits or not. i having problem on hasdistinctintegers method. doesn't evaluate should. true if number not have repeating digits, false if does. believe other methods working correctly, utilize set of eyes! here have far:

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++; } homecoming returner; } public static int numdigits(int number) { int count = 0; while (number != 0) { number /= 10; count++; } homecoming 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)) { homecoming -1; } else { homecoming 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++; } homecoming index; }

thanks in advance tips/advice!

using set<integer> can code such:

public static boolean hasdistinctdigits(int number) { final set<integer> set = new hashset<integer>(); while (number > 0) { if (!set.add(number % 10)) homecoming false; number /= 10; } homecoming true; }

you can utilize plain array:

public static boolean hasdistinctdigits(int number) { // rely on java's default values here: // uninitialized ints set 0. final int[] digits = new int[10]; // peace of mind, can... arrays.fill(digits, 0); int digit; while (number > 0) { digit = number % 10; if (digits[digit]++ > 0) homecoming false; number /= 10; } homecoming true; }

please note both methods above don't check whether argument greater 0.

using java 8, can have more fun:

public static boolean hasdistinctdigits(int number) { final set<integer> set = new hashset<>(); homecoming string.valueof(number).chars().allmatch(set::add); }

but @ level, intellectual masturbation, really... (or (int)stream abuse -- pick)

java loops while-loop int nested

No comments:

Post a Comment