Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The solution and a test-case (for single digit number) have been added. #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion src/main/java/org/jugbd/marathon/day2/BiggestNumber.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,29 @@ public class BiggestNumber {
public static long findTheNextBiggerNumber(long n) {
//write your awesome code here

return n;
StringBuilder originalNumStr = new StringBuilder(String.valueOf(n));
int numOfDigits = originalNumStr.length();
return finderHelper(n, n, 1, numOfDigits);
}
private static long finderHelper(long originalNumber, long currentNumber, int index, int numOfDigits) {
if (currentNumber / 10 != 0) {
long swappedNumber;
swappedNumber = swap(originalNumber, numOfDigits - index, numOfDigits - index - 1);
if (swappedNumber > originalNumber) {
return swappedNumber;
}
return finderHelper(originalNumber, currentNumber / 10, index + 1, numOfDigits);
} else {
return -1;
}
}

private static long swap(long number, int firstIndex, int secondIndex) {
StringBuilder numberStr = new StringBuilder(String.valueOf(number));
char temp;
temp = numberStr.charAt(firstIndex);
numberStr.setCharAt(firstIndex, numberStr.charAt(secondIndex));
numberStr.setCharAt(secondIndex, temp);
return Long.valueOf(numberStr.toString());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public void basicTests() {
assertEquals(2071, BiggestNumber.findTheNextBiggerNumber(2017));
assertEquals(441, BiggestNumber.findTheNextBiggerNumber(414));
assertEquals(414, BiggestNumber.findTheNextBiggerNumber(144));
assertEquals(-1, BiggestNumber.findTheNextBiggerNumber(7));
assertEquals(-1, BiggestNumber.findTheNextBiggerNumber(111));
assertEquals(-1, BiggestNumber.findTheNextBiggerNumber(531));
}
Expand Down