CC-7 : Check if number is fascinating.
Description:
For a number num, if we add 2*num and 3*num to num, then if the resultant number contains all digits from 1 to 9 only once, then the number num is said to be fascinating. Given number num as input, return true if num is fascinating, else return false.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| The input number is: 273 | 273 is a fascinating number |
| The input number is: 219 | 219 is a fascinating number |
| The input number is: 999 | 999 is *not* a fascinating number |
Pseudocode:
| The java method should accept following input parameters: num (integer). |
| Initialize a StringBuilder sb. |
| Append num, 2*num, 3*num to sb. |
| Initialize a char array chars and set it to extracted characters from sb. |
| Initialize a variable intCntMap of type HashMap |
| Iterate through chars using a for loop with idx as a loop variable with initial value 0 and increment idx till it reaches chars.length-1:
If intCntMap does not contain key equal to chars[idx]:
Add key chars[idx] and add value 1 to intCntMap.
If intCntMap contains key equal to chars[idx]:
Add key chars[idx]and add value equal to current value of key chars[idx], incremented by 1 to intCntMap.
|
| After completion of above loop, intCntMap contains all digits of sb as keys and the counts of these digits in sb as values. |
| Using a for loop with idx as a loop variable with initial value 1 and increment idx till it reaches 9:
If intCntMap does not contain key idx and value 1, return false from the program.
|
| If the above loop completes successfully till idx 9 without returning false from the program, that means the num is a fascinating number, so return true. |
Code:
public boolean hashMapChkFascinating(int num1) throws Exception{
int num2=2*num1;
int num3=3*num1;
StringBuilder sb=new StringBuilder();
sb.append(num1);
sb.append(num2);
sb.append(num3);
System.out.println("\n\nThe appended number is: "+sb.toString());
char[] chars=new char[sb.length()];
sb.getChars(0, sb.length(), chars, 0);
HashMap< Character,Integer> intCntMap=new HashMap<Character, Integer>();
for (int idx=0; idx < chars.length; idx++) {
intCntMap.put(chars[idx], intCntMap.getOrDefault(chars[idx],0)+1);
}
if (intCntMap.get('0') != null) {return false;}
char c;
for (int idx=1; idx <= 9; idx++) {
c=Character.forDigit(idx, 10);
if (intCntMap.getOrDefault(c,0)!=1) {
return false;
}
}
return true;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |