Last active
January 14, 2019 08:32
-
-
Save kylelong/597fe9585c59f7313254d8a6b8a0e941 to your computer and use it in GitHub Desktop.
Week 1/13/19 of cassido's newsletter interview question of the week.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
/** | |
* Returns all numbers < n whose digits are 1 or 5. | |
* Created by Kyle Long on 1/14/19. | |
*/ | |
public class oneFive { | |
public static void main(String [] args){ | |
Scanner scan = new Scanner(System.in); | |
int n = scan.nextInt(); | |
System.out.println(oneOrFive(n)); | |
} | |
/** | |
* Returns string of all numbers < n that contain only 1s or 5s | |
* @param n The number to iterate | |
* @return String of all digits < n that contain only 1s or 5s | |
*/ | |
public static String oneOrFive(int n){ | |
ArrayList<Integer> list = new ArrayList<>(); | |
for(int i = 1; i < n; i++){ | |
if(hasOnlyOneOrFive(i)){ | |
list.add(i); | |
} | |
} | |
return Arrays.deepToString(list.toArray()); | |
} | |
/** | |
* Checks if a number only has 1s or 5s | |
* @param n The number to check | |
* @return Whether or not n contains only 1s or 5s | |
*/ | |
public static boolean hasOnlyOneOrFive(int n){ | |
int lastDigit = 0; | |
while(n != 0){ | |
lastDigit = n % 10; | |
if(lastDigit != 1 && lastDigit != 5){ | |
return false; | |
} | |
n /= 10; | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment