Modify the given file Sixes.java to return the number of sixes contained in the
ID: 3917353 • Letter: M
Question
Modify the given file Sixes.java to return the number of sixes contained in the numbers supplied. This must be a recursive solution. Non-recursive solutions will not receive credit. Remember, to be a recursive solution, your method must call itself. You should not have a loop anywhere in this program.
Sample output:
66776 has 3 sixes.
123456 has 1 sixes.
111223 has 0 sixes.
666666 has 6 sixes.
868686838 has 3 sixes.
6241 has 1 sixes.
public class Sixes
{
public static void main(String[] args)
{
System.out.println("66776 has " + getSixes(66776) + " sixes.");
System.out.println("123456 has " + getSixes(123456) + " sixes.");
System.out.println("111223 has " + getSixes(111223) + " sixes.");
System.out.println("666666 has " + getSixes(666666) + " sixes.");
System.out.println("868686838 has " + getSixes(868686838) + " sixes.");
System.out.println("6241 has " + getSixes(6241) + " sixes.");
System.out.println("776 has " + getSixes(776) + " sixes.");
}
public static int getSixes(int num)
{
//Enter your code here
}
}
Explanation / Answer
class Main
{
public static void main(String[] args)
{
System.out.println("66776 has " + getSixes(66776) + " sixes.");
System.out.println("123456 has " + getSixes(123456) + " sixes.");
System.out.println("111223 has " + getSixes(111223) + " sixes.");
System.out.println("666666 has " + getSixes(666666) + " sixes.");
System.out.println("868686838 has " + getSixes(868686838) + " sixes.");
System.out.println("6241 has " + getSixes(6241) + " sixes.");
System.out.println("776 has " + getSixes(776) + " sixes.");
}
public static int getSixes(int num)
{
//Enter your code here
if(num==0) //base case
return 0;
if(num%10==6) //found 6 case
return 1+getSixes(num/10); // adding one and recursively calling with the rest of the number
return getSixes(num/10);//other number case
}
}
/*
Sample output:
66776 has 3 sixes.
123456 has 1 sixes.
111223 has 0 sixes.
666666 has 6 sixes.
868686838 has 3 sixes.
6241 has 1 sixes.
776 has 1 sixes.
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.