Tuesday, 15 July 2014

java - Check if integer has repeating digits. No string methods or arrays -



java - Check if integer has repeating digits. No string methods or arrays -

i'm trying see if int has multiples of same digit. trying without string methods or arrays. main method i'm having problem hasdistinctdigits(). works when repeating digits @ end, not when come @ origin or middle.

public static void main(string[] args) { system.out.println(hasdistinctdigits(12234)); } public static boolean hasdistinctdigits(int number) { boolean returner = true; int count = 1; int newnum = number; int digit = 0; while (count < numdigits(number)) { while (count < numdigits(newnum)) { digit = newnum % 10; newnum/=10; if (digit == getdigit(newnum, count)) { returner = false; } count++; } count++; } 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; } }

}

if run, see '2' repeats itself, method still evaluates true when should false.

you need check each digit every other digit. suggests should have @ to the lowest degree 2 nested loops. seem have mixed them both.

have 1 loop digit beingness checked , other iterating on other digits.

also, getdigit method not working correctly. replace with

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; } }

hope helps. luck.

java loops while-loop int

No comments:

Post a Comment