Advertisement
Guest User

Untitled

a guest
May 29th, 2015
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. package dfs;
  2.  
  3. class SteppingNumber {
  4. public static void findSteppingNum(int start, int end) {
  5. if(start > end) {
  6. System.out.println("Invalid input");
  7. return;
  8. }
  9. int tend = end;
  10. int tstart = start;
  11. int digitCount = 0;
  12. //find the very first digit of start; digitCount will be the depth of DFS
  13. while (tstart >= 10) {
  14. tstart /= 10;
  15. tend /= 10;
  16. digitCount++; //the number of digit needs to be filled out
  17. }
  18. int diff = tend - tstart;
  19. for(int i=0; i<=diff; i++) {
  20. //make sure the starting num is stepping number
  21. if(isStepping(tstart + i))
  22. helper(tstart + i, digitCount, start, end);
  23. }
  24. }
  25. public static void helper(int currNum, int remains, int start, int end) {
  26. if(remains == 0) {
  27. if(start <= currNum && currNum <= end) {
  28. System.out.println(currNum);
  29. }
  30. return;
  31. }
  32. int endDigit = currNum%10;
  33. //step down
  34. if(endDigit > 1) {
  35. int down = currNum*10 + endDigit - 1;
  36. helper(down, remains - 1, start, end);
  37. }
  38. //step up
  39. if(endDigit < 9) {
  40. int up = currNum*10 + endDigit + 1;
  41. helper(up, remains - 1, start, end);
  42. }
  43. }
  44. public static boolean isStepping(int num) {
  45. int lastDigit = num%10;
  46. num /= 10;
  47. while(num > 0) {
  48. int currentDigit = num%10;
  49. if(!(lastDigit - 1 == currentDigit || lastDigit + 1 == currentDigit))
  50. return false;
  51. num/=10;
  52. }
  53. return true;
  54. }
  55. public static void main(String...args) {
  56. findSteppingNum(1, 500); //23
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement