Im stuck with the below problem.
Problem Statement:
Given a non-negative int n, return the count of the occurrences of 8 as a digit, except that an 8 with another 8 immediately to its left counts double, so 8818 yields 4.
Note: mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).
The above problem has to be solved without using Recursion and without the usage of any formulas.
The function signature is public int count8(int n)
Examples are:
count8(8) → 1
count8(818) → 2
count8(8818) → 4
I got this problem from one of the Programming Forums. I dont know how to start with this problem, I want to solve it, but I am really confused on where to begin.
the way to do this using the mod operator is to use %10 to get the last digit and /10 to remove the last digit in essence iterating through the number. If you %10 and get an 8 you can incremement a count, you can also keep a flag that lets you know if the last digit you saw was an 8 or not so you know how to increment your count
boolean lastWas8 = false;
int count = 0;
while (n != 0)
{
int digit = n % 10;
if (digit == 8)
{
if (lastWas8) count++;
count++;
lastWas8 = true;
}
else lastWas8 = false;
n/=10;
}
return count;
As none of the answers until now was recursive, here is my try at a recursive solution.
public int count8(int n) {
return
n <= 0 ? 0 :
( n%100 == 88 ? 2 :
n%10 == 8 ? 1 : 0)
+ count8(n/10);
}
Here the same program in a longer version:
public int count8(int n) {
Numbers without digits have no eights in them.
if(n <= 0) {
return 0;
}
Count the last digit:
int last;
If the last digit is an 8 and the digit before, too, count the last 8 doubled:
if(n % 100 == 88) {
last = 2;
}
If the last digit is an 8 (and the one before not), count it once.
else if(n % 10 == 8) {
last = 1;
}
Otherwise, the last digit is not an 8:
else {
last = 0;
}
The number without the last digit:
int withoutLast = n/10;
The number of eights in n is the number of eights in the last digit + the number of eights in the number without its last digit:
return last + count8(withoutLast);
}
Since I misread the question, here a iterative version of the same algorithm:
public int count8(int n) {
int count = 0;
while(n > 0) {
count += ( n%100 == 88 ? 2 : n%10 == 8 ? 1 : 0);
n/= 10;
}
return count;
}
Or with a for-loop:
public int count8(int n) {
int count = 0;
for( ; n > 0; n/=10) {
count += ( n%100 == 88 ? 2 : n%10 == 8 ? 1 : 0);
}
return count;
}
I saw that all the other solutions have used mods or divs but you could also just process it as a String I guess (I don't see anything in the question that says you can't despite the hints they give you). This is just an alternative solution.
I apologise in advance if I have missed some of the "rules" around the answer to this question but here we go anyway:
private int count8(int n) {
String nString = Integer.toString(n);
boolean isPrevChar8 = false;
int total = 0;
for (int i = 0; i < nString.length(); i++) {
char nextChar = nString.charAt(i);
if (nextChar == '8') {
total += (isPrevChar8 ? 2 : 1);
isPrevChar8 = true;
} else {
isPrevChar8 = false;
}
}
return total;
}
try this :
public static int count8(int num) {
int count=0;
boolean doubl = false;
while(true) {
int n = num%10;
num = num/10;
if(n==8) {
if(doubl) {
count = count+2;
} else {
count++;
}
doubl=true;
}
else {
doubl=false;
}
if(num == 0) break;
}
return count;
}
EDIT: Check this out for no recursion and no formula.
public static int count8(int num) {
int count=0;
boolean doubl = false;
String str = "" + num;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '8') {
if (doubl) {
count = count + 2;
} else {
count++;
}
doubl = true;
} else {
doubl = false;
}
}
return count;
}
Here is my solution:
public int count8(int n) {
int count = 0;
if(n == 0)
return 0;
if(n % 100 == 88)
{
count = 3;
return count + count8(n/100);
}
else if(n % 10 == 8)
{
count++;
return count + count8(n/10);
}
else
return count8(n/10);
}
However, for the case: count8(88888) → 9, I get 7, and I can't figure out why.
What I also find strange is that a double 8 yields 3 so for the case: count8(8818) → 4 instead of 5, which is what I thought it would be. Hence, why I have count = 3 for the (n % 100 == 88)
Here is my code . The solution to this problem is very simple . I have done it with pure recursion . :)
public int count8(int n) {
if (n==8) return 1;
if (n<10) return 0;
if (n%100==88)
return 2 + count8(n/10);
if (n%10==8)
return 1 + count8(n/10);
return count8(n/10);
}
The catch of the problem is that when a pair of 88 comes total count = 1 + 2 ; 1 for 8 at right and 2 for 8 at left because the previous digit(which is digit at its adjacent right) was also 8 .
So for 88 the total occurances of 8 is equal to 3. For implementing this logic (n%100 ==88) condition is added .
This is the another recursion technique which I have used to solve this problem :-
public int count8(int n) {
int a,b;
if(n==0)
return 0;
a=n%10;
b=(n/10)%10;
if(a==8&&b==8)
return 2+count8(n/10);
else if(a==8&&b!=8)
return 1+count8(n/10);
else
return count8(n/10);
}
This code also works;
public int count8(int n) {
if(n/10 == 0 && n%10 != 8){
return 0;
}
if(n % 10 == 8 && (n/10)%10 == 8){
return 2 + count8(n/10);
}
if(n/10 == 0 && n%10 == 8){
return 1 + count8(n/10);
}
if(n % 10 != 8){
return 0 + count8(n/10);
}else{
return 1 + count8(n/10);
}
}
Here is simple solution
public int count8(int n) {
//base case if n becomes 0 then return 0
if(n==0) return 0;
//checking for two consecutive 8's in a row
if((n%10) == 8 && (n/10)%10 == 8){
return 2 + count8(n/10);
}
else if(n%10 == 8){ // there is only one 8
return 1 + count8(n/10);
}
//no 8 found
return count8(n/10);
}
Here's my solution, albeit the function names aren't nicely named, just think of them as abstract (not in the Java abstract keyword sense) functions that perform their task.
public int count8(int n) {
return g(n, 0);
}
public int g(int n, int prev) {
int rest = n/10;
int digit = n % 10;
if (rest == 0) {
return h(digit, prev);
}
int toAdd = h(digit, prev);
return toAdd + g(rest, digit);
}
public int h(int digit, int prev) {
return prev == 8 && digit == 8 ?
2 : digit == 8 ?
1 : 0;
}
Related
I am trying to make a program to display the first 50 prime palindromes with 10 numbers per line. This is the code i have so far, however when run nothing happens. I have looked t similar solutions and can't seem to find were the error is. Any help would be appreciated.
import java.lang.Math;
public class PalindromicPrime {
public static void main(String[] args) {
int counter = 1;
int start = 2;
isPalindrome(start);
isPrime(start);
while (counter <= 50) {
if (isPrime(start) && isPalindrome(start)) {
System.out.print(start + " ");
if (counter % 10 == 0) {
System.out.println();
counter++;
}
start++;
}
}
}
public static boolean isPalindrome(int x) {
int reverse = 0;
while(x > 0) {
reverse = reverse * 10 + x % 10;
x = x / 10;
}
if (reverse == x) {
return true;
}
else {
return false;
}
}
public static boolean isPrime(int x) {
if (x % 2 == 0 && x != 2) {
return false;
}
int sqr = (int)Math.sqrt(x);
for (int i = 3; i <= sqr; i += 2) {
if(x % i == 0) {
return false;
}
}
return true;
}
}
You're not incrementing start when it isn't prime, so you hit an infinite loop when you hit your first non-prime number. Put your start++ outside of the if statement.
Your isPalindrome() method is broken. The variable x is whittled down to create reverse, but then you compare reverse to the modified version of x instead of its original value.
You're only incrementing counter every 10th prime, so this will end up printing 500 palindromic primes, not 50.
Bonus: Finding primes is faster if you store every prime that you find, and then only check division by previously-found primes.
First of all as others have said your isPalindrome() Method is not working correctly.
I would suggest you just convert your int to a string and then check whether that is a Palindrome. I think it is the easiest way. Maybe others can comment whether that is a bad idea in terms of performance.
Here is how I would do it:
public static boolean isPalin(int x) {
String s = Integer.toString(x);
for(int i = 0; i < s.length()/2; i++) {
if(s.charAt(i) != s.charAt(s.length()-i-1)) {
return false;
}
}
return true;
}
Also your while loop is not working correctly as you only increment start when you actually found a prime. Counter should be incremented everytime you found a prime.
On top of that you should base the condition for the while loop on your start value and not the counter for the line breaks.
Edit: Actually you should use counter in the while condition. I was wrong.
Here is the updated code:
public static void main(String[] args) {
int counter = 0;
int start = 2;
while (counter < 50) {
if (isPrime(start) && isPalin(start)) {
System.out.print(start + " ");
counter++;
if (counter % 10 == 0) {
System.out.println();
}
}
start++;
}
}
public static boolean isPalin(int x) {
String s = Integer.toString(x);
for(int i = 0; i < s.length()/2; i++) {
if(s.charAt(i) != s.charAt(s.length()-i-1)) {
return false;
}
}
return true;
}
public static boolean isPrime(int x) {
if (x % 2 == 0 && x != 2) {
return false;
}
int sqr = (int)Math.sqrt(x);
for (int i = 3; i <= sqr; i += 2) {
if(x % i == 0) {
return false;
}
}
return true;
}
Here is the output for the first 50 primes that are palindromic:
2 3 5 7 11 101 131 151 181 191
313 353 373 383 727 757 787 797 919 929
10301 10501 10601 11311 11411 12421 12721 12821 13331 13831
13931 14341 14741 15451 15551 16061 16361 16561 16661 17471
17971 18181 18481 19391 19891 19991 30103 30203 30403 30703
Your code is an Infinite looping. This is because you increment start in the if statement, so only when start is a prime and palindrome number.
If start isn't palindrome or prime, it will not enter the conditional and thus counter will Nevers incréée and reach 50
In this program I am supposed to figure out if the integer that the user enters contains a certain digit (in this case 7 and 3), and then return a boolean. So far I have:
public static boolean contains(int num, int x) {
Scanner input = new Scanner(System.in);
int currentLength = numberDigits(num); //method that counts the number of digits in the inputed integer
int digit; // current first digit
int firstNumber = firstNum(num);
boolean digitTrue = false;
while (currentLength > 0 ) {
digit = firstNumber;
if (num == x)
{
digitTrue= true;
} else {
digitTrue= false;
}
}
return digitTrue;
}
By invoking module 10 on a number you retrieve the last digit of this number.
Perform it on num, then perform it on num/10, then on num/100 until you iterates on all digits (that is while the division result > 0).
You could so write :
int currentNumber = num;
while (currentNumber > 0 ) {
if (currentNumber % 10 == x){
return true;
}
currentNumber = currentNumber / 10;
}
return false;
Note that the boolean variable is helpless.
You want to return true as soon as a digit equals to x, so return true directly in the conditional statement block and return false; after the while statement.
This code works correctly for contains (0, 0) too:
boolean contains (int num, int x) {
do {
if (num % 10 == x){
return true;
}
num /= 10;
} while (num > 0);
return false;
}
For x > 9 or x < 0, you have to write an guard statement and for num (and/or x) < 0 you should take the Math.abs first.
The best way to solve this that I know of is to use %. % or Modulus returns the remainder of one number / by another number. For example 5 % 2 = 1 or 355 % 10 = 5. If you are looking only to check a large number for single digit numbers I would suggest this method
public static boolean contains(int num, int x){
while(num >= 0){
if (num % 10 == x){
return true;
}
if (num > 0){
num = num / 10;
}else{
return false;
}
}
return false;
}
Hope this Helps
I had an interview in which I did terribly. So, now I'm trying to find the solution to the question. Here is the interview question:
"We have the following mapping:
M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1.
And we have the following rules:
Each letter maps to a positive integer value
You add the values together, except...
...when a value (or runs of the same values) is followed by a greater value, you subtract the total of that run of values.
Examples:
IIX -> 8
MCCMIIX -> 1808
We are given this Java method: int valueOfRoman(char roman).
We have implement the Java method: int romanToInt(String s)"
I know it is not a proper roman number system, but that is the actual question.
I was able to code a working solution to a proper Roman system. But I'm unable to change it so that it adapts to these new rules, particularly Rule 3. I have tried, but with no success. The way my solution is right now, for IIX, it prints 10, instead of the correct answer of 8. Here is my code (I also implemented valueOf for my testing):
static int romanToInt(String s) {
char curr;
int currVal;
char prev;
int prevVal;
int total = valueOfRoman(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
curr = s.charAt(i);
currVal = valueOfRoman(curr);
prev = s.charAt(i-1);
prevVal = valueOfRoman(prev);
total += currVal;
if(currVal > prevVal) {
total = total - (2*prevVal);
}
}
return total;
}
static int valueOfRoman(char c) {
if (c == 'M') {
return 1000;
} else if (c == 'D') {
return 500;
} else if (c == 'C') {
return 100;
} else if (c == 'L') {
return 50;
} else if (c == 'X') {
return 10;
} else if (c == 'V') {
return 5;
} else if (c == 'I') {
return 1;
}
return -1;
}
Any help is really appreciated. Specially useful would be if you can tell me how to modify my code. Thanks!
EDIT: I edited the names of the methods so they are clearer.
My take - works with the admittedly small tests you supplied.
static int rom2int(String s) {
if (s == null || s.length() == 0) {
return 0;
}
// Total value.
int total = 0;
// The most recent.
char current = s.charAt(0);
// Total for the current run.
int run = valueOf(current);
for (int i = 1; i < s.length(); i++) {
char next = s.charAt(i);
int value = valueOf(next);
if (next == current) {
// We're in a run - just keep track of its value.
run += value;
} else {
// Up or down?
if (value < valueOf(current)) {
// Gone down! Add.
total += run;
} else {
// Gone UP! Subtract.
total -= run;
}
// Run ended.
run = valueOf(next);
}
// Kee track of most recent.
current = next;
}
return total + run;
}
private void test(String s) {
System.out.println("Value of " + s + " = " + rom2int(s));
}
public void test() {
test("IVX");
test("IIVVL");
test("IIX");
test("MCCMIIX");
test("MVVV");
}
prints
Value of IVX = 4 - Odd!!!
Value of IIVVL = 38
Value of IIX = 8
Value of MCCMIIX = 1808
Value of MVVV = 1015
Here's how I'd approach the problem:
Read the string character by character and during every step note the current character and the previous character.
If the current character is the same as the previous, increase the run length by 1.
If the current character has a smaller value than the previous, add run length * value of previous character to the total, and reset run length to 1.
If the current character has a greater value than the previous, subtract run length * value of previous character from the total, and reset run length to 1.
So, nobody caught my hint. Then I'll give it a try, too. I won't go into the "IVX"- thing because I consider that a syntax error.
int romanToInt( String s ){
int total = 0;
int pivot = 0;
for( int i = s.length()-1; i >= 0; i--){ // We start at the **end**
int current = valueOfRoman((s.charAt(i));
if( current >= pivot ){ // We will have at least "I", so it **will** be > pivot for 1st char.
pivot = current;
total += pivot;
}else{
total -= current;
}
}
return total;
}
Let's see: IIX
i char value total pivot -> total pivot
2 X 10 0 0 > 10 10
1 I 1 10 10 < 9 10
0 I 1 9 10 < 8 10
MCCMIIX
i char value total pivot -> total pivot
6 X 10 0 0 > 10 10
5 I 1 10 10 < 9 10
4 I 1 9 10 < 8 10
3 M 1000 8 10 > 1008 1000
2 C 100 1008 1000 < 908 1000
1 C 100 908 1000 < 808 1000
0 M 1000 808 1000 = 1808 1000
The method leaves out input validation for brevity. I am assuming all input has been checked and consists only of allowed characters according to "the rules".
My take on it.
EDIT CHANGE #2
public class Romans {
private int valueOf(char c) {
if (c == 'M') {
return 1000;
} else if (c == 'D') {
return 500;
} else if (c == 'C') {
return 100;
} else if (c == 'L') {
return 50;
} else if (c == 'X') {
return 10;
} else if (c == 'V') {
return 5;
} else if (c == 'I') {
return 1;
}
return 0;
}
public int rom2int(String s) {
int currVal;
int runValue = 0;
int repetition = 0;
int total = 0;
boolean alreadyAdded = false;
for (int i = 0; i < s.length(); i++) {
currVal = valueOf(s.charAt(i));
if (runValue == 0) {
runValue = currVal;
repetition = 1;
alreadyAdded = false;
} else if (currVal > runValue) {
total = total + (currVal - (runValue * repetition));
repetition = 1;
runValue = currVal;
alreadyAdded = true;
} else if (currVal < runValue) {
if(!alreadyAdded) {
total += (runValue * repetition);
}
repetition = 1;
runValue = currVal;
alreadyAdded = false;
} else {
repetition++;
alreadyAdded = false;
}
}
if (!alreadyAdded) {
total += (runValue * repetition);
}
return total;
}
}
And the main I'm running:
public static void main(String[] args) {
Romans r = new Romans();
String[] inputs = {"MVVV", "IIX","MCCMIIX", "IVX"};
for(String input : inputs) {
System.out.println("Value of " + input + " is: " + r.rom2int(input));
}
}
Outputs:
Value of MVVV is: 1015
Value of IIX is: 8
Value of MCCMIIX is: 1808
Value of IVX is: 9
That's how I did.
It works for those 2 values you mentioned (IIX = 8 and MCCMIIX = 1808):
public static int rom2int(String s)
{
int currVal = 0, prevVal = 0, subTotal = 0, total = 0;
for (int i = 0; i < s.length(); i++) {
currVal = valueOf(s.charAt(i));
if (currVal > 0) {
if (prevVal == 0) {
subTotal = currVal;
}
else if (currVal > prevVal) {
total += (currVal - subTotal);
subTotal = 0;
}
else if (currVal < prevVal) {
total += subTotal;
subTotal = currVal;
}
else if (currVal == prevVal) {
subTotal += currVal;
}
prevVal = currVal;
}
}
total += subTotal;
return total;
}
public static int valueOf(char c)
{
if (c == 'M')
return 1000;
if (c == 'D')
return 500;
if (c == 'C')
return 100;
if (c == 'L')
return 50;
if (c == 'X')
return 10;
if (c == 'V')
return 5;
if (c == 'I')
return 1;
return 0;
}
EDIT 1:
Explanation for "IVX" value:
"...add values together except when a value (or runs of the SAME
values) is followed by a greater value, you subtract the total of that
run of values."
IVX = 1 5 10
if 5 > 1 then 5 - 1 = 4
if 10 > 5 then 10 - 0(*) = 10 (*) we already have used V(5) before, so we discard it.
So the answer for IVX is 14!
My approach would be to break the problem into the following steps:
Create a map of the symbols and values (a roman map).
Create a store to keep your result.
Loop through all the strings from RTL.
For each symbol, check that the value of the current symbol is greater than its previous value.
If the current symbol is greater than its previous value (e.g IV, where V is the current symbol), then do subtraction (current value minus previous value) and add that to the result; then skip the previous value in the loop.
Else; add the value of the current symbol to the result.
Note:
An important rule to note is that there can only be 1 prev value in the roman numerals to indicate a reduction.
IV = 4
IIV = invalid
...same with the rest of the numerals (IXCVDM...).
Hope this helps someone in the future.
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
romanMap = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 }
result = 0;
index = len(s) - 1;
while (index >= 0):
romanValue = s[index];
prevValue = s[index - 1];
if ((index > 0) and (romanMap[romanValue] > romanMap[prevValue])):
result += romanMap[romanValue] - romanMap[prevValue];
index-= 1;
else:
result += romanMap[romanValue];
index-= 1;
return result;
You can run the code with the following:
print(Solution().romanToInt("LVIII"));
this kind of problematics are usually really easy to solve using recursive way of thinking. The solution could look like :
public int rom2int(String s)
{
if(s.length() == 0)
// no string --> 0
return 0;
else if(s.length() == 1)
// One Character --> Value of Character
return valueOf(s.charAt(0));
else if((valueOf(s.charAt(0)) > valueOf(s.charAt(1))) )
// The value is NOT followed by a greater value --> We had the value
return rom2int(s.substring(1, s.length())) + valueOf(s.charAt(0));
else if(valueOf(s.charAt(0)) <= valueOf(s.charAt(1)) )
// The value is followed by a greater (or same) value --> We substract the value
return rom2int(s.substring(1, s.length())) - valueOf(s.charAt(0));
else
// Shouldn't Happen. 0 as neutral element in in a Sum.
return 0;
}
Even if recursive solution is forbidden, to my mind it is simpler to un-recursive this algorithm than find the procedural one at first try =)
Edit :
MY Results :
Value of MCCMIIX is : 1808
Value of IIX is : 8
Value of IVX is : 4
Value of IIVVL is : 38
Can anybody help me programming the next problem (taken from Codingbat- Recursion1- count7)
Given a non-negative int n, return the count of the occurrences of 7 as a digit, so for example 717 yields 2. (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).
count7(717) → 2
count7(7) → 1
count7(123) → 0
There are some solutions which includes number of "returns".
I would like to program the problem with only 1 "return".
Well here's the solution I wrote and let's see how to do it with only one return
public int count7(int n)
{
int c = 0;
if (7 > n)
{
return 0;
}
else
{
if ( 7 == n % 10)
{
c = 1;
}
else
{
c = 0;
}
}
return c + count7(n / 10);
}
the same with only one return
public int count7(int n)
{
return (7 > n) ? 0 : ( ( 7 == n % 10) ? 1 + count7(n / 10) : 0 + count7(n / 10));
}
public int count7(int n) {
int counter = 0;
if( n % 10 == 7) counter++;
if( n / 10 == 0) return counter;
return counter + count7(n/10);
}
Sure PFB my solution in JAVA for the same
public int count7(int n) {
if((n / 10 == 0) && !(n % 10 == 7)) //First BASE CASE when the left most digit is 7 return 1
return 0;
else if((n / 10 == 0) && (n % 10 == 7)) //Second BASE CASE when the left most digit is 7 return 0
return 1;
else if((n % 10 == 7))
//if the number having 2 digits then test the rightmost digit and trigger recursion trimming it there
return 1 + count7(n / 10);
return count7(n / 10);
}
public int count7(int n) {
if(n == 0)
return 0;
else{
if(n%10 ==7)
return 1+count7(n/10);
return 0+count7(n/10);
}
}
public static int count7(int n){
if(n == 7)
return 1;
else if(n > 9){
int a = count7(n%10);
int b = count7(n/10);
return a + b;
}else
return 0;
}
public int count7(int n)
{
if(n==0)return 0;
if(n%10==7)return 1+count7(n/10);
else return count7(n/10);
}
public int count7(int n) {
if (n != 7 && n < 10) return 0;
else if (n == 7) return 1;
else if (n%10 == 7) return count7(n/10) + 1 ;
else return count7(n/10);
}
public int count7(int n){
if(n < 7)
return 0;
else if(n % 10 == 7)
return 1 + count7(n / 10);
else
return count7(n / 10);
}
the first if-statement is the base case that we would want to terminate on. The second checks to see if the rightmost digit is 7. If it is, chop the rightmost digit off and try again. When the recursive calls terminate and and values start getting returned up the chain, add 1 to include this successful check. In the case that neither of the above statements are true, chop off the rightmost digit and try again.
I know this is 2 years old, but hope this is a bit more readable and intuitive, and thus helpful.
Here is how I did it.
public int count7(int n) {
return (n==0?0:(count7(n/10)+(n%10==7?1:0)));
}
Recursion goes to 0 and it returns 0, when it comes back out checks if each number is 7, returns 1 if it is else 0. It continues adding those until all the way out.
Using one return will likely make it harder to read. If you are counting occurrences in recursion, an easy formula is to create a base case to terminate on, then provide an incremental return, and finally a return that will aid in reaching the base case without incrementing. For example..
public int count7(int n) {
if(n == 0) return 0;
if(n % 10 == 7) return 1 + count7(n / 10);
return count7(n / 10);
}
Using a one liner return like the one below in my opinion is harder to read or update because of the double ternary..
public int count7(int n)
{
return (n == 0) ? 0 : (n % 10 == 7) ? 1 + count7(n / 10) : count7(n / 10);
}
My solution works backwards from the nth digit to the first digit, by taking the modulus of the input. we add the number of sevens found into the return, for the final output.
Then checking whether the input is less than 7 can be the next step. If the input is less than 7 then there have never been any 7s in the input to begin with.
public int count7(int n) {
int sevens_found = 0;
if( n % 10 == 7 ) sevens_found ++;
return ( n < 7) ? 0 : ( n % 10 == 7 ) ? sevens_found + count7 ( n / 10 ) : count7 ( n / 10 );
}
#include<bits/stdc++.h>
using namespace std;
int count_occurences(int k){
int r;
if(k==0){
return 0;
}
r = k%10;
k = k/10;
if(r!=7){
return count_occurences(k);
}
return 1+count_occurences(k);
}
int main()
{
int x;
cin>>x;
cout<<" "<<count_occurences(x);
return 0;
}
public int count7(int n) {
int length = 0;
int counter = 0;
if ((n / 10) * 10 != n || (n / 10) != 0) {
if (n % 10 != 7) {
counter++;
}
length += 1 + count7(n / 10);
}
return length - counter;
}
The base case of n == 0 just "breaks" us out of the recursive loop, the n % 10 == 7 allows us to actually count the amount of 7s in an integer, and the return statement iterates through the given argument.
public int count7(int n) {
if (n == 0)
return 0;
if (n % 10 == 7)
return 1 + count7(n / 10);
return count7(n / 10);
}
public int count7(int n)
{
return occurrencesCounting(n, 0);
}
private int occurrencesCounting(int n, int count)
{
int counter = n % 10 == 7 ? count + 1 : count;
if (n / 10 == 0)
{
return counter;
}
return occurrencesCounting(n / 10, counter );
}
I need help in figuring out how to return the sum of all numbers in a 2d array entered from a keyboard which are divisible by three. I have my compute sum method that will return one test case correctly, however it does not calculate correctly for every case given. Any suggestions would be very helpful. I will load my code including the while loop to make it easier to find where I am calculating wrong.
try
{
InputStreamReader stream = new InputStreamReader (System.in);
BufferedReader scan = new BufferedReader(stream);
inputParser = Integer.parseInt(input);
int i = 0;
while(inputParser != 0)
{
input = scan.readLine();
inputParser = Integer.parseInt(input);
if(inputParser == 0)
{
inputParser = 0;
}
else
{
numbers1[i] = inputParser;
i++;
}
}
sum = computeSumDivisibleBy3(numbers1,0,numbers1.length-1);
System.out.println("The sum of the numbers divisible by 3 is " + sum);
}
catch(NumberFormatException exception)
{
System.out.println("Please enter integers only");
}
here is the method to calculate the sum divisible by 3
//instead of this original method, I've implemented yours just below this and it returns correctly
public static int computeSumDivisibleBy3(int[] numbers, int startIndex, int endIndex){
if (startIndex == endIndex)
return numbers[endIndex];
else{
int sum1 = computeSumDivisibleBy3(numbers, startIndex, endIndex-1);
if (numbers[endIndex] % 3 == 0)
return sum1 + numbers[endIndex];
else
return sum1;
}
}
//newly implemented code
public static int computeSumDivisibleBy3(int[] numbers, int startIndex, int endIndex){
if (startIndex == numbers.length-1)
return numbers[startIndex] % 3 == 0 ? numbers[startIndex] : 0;
else{
return (numbers[startIndex] % 3 == 0 ? numbers[startIndex] : 0) + computeSumDivisibleBy3( numbers, ++startIndex, endIndex );
}
}
// is startIndex really needed? you only ever use it unnecessarily, so, no.
public static int computeSumDivisibleBy3(int[] numbers, int startIndex, int endIndex){
// End condition, good, but the return value doesn't make any sense
// You always return the last one in the array, even it's not divisible by 3
//if (startIndex == endIndex)
// return numbers[endIndex];
// How about this instead (taking the removal of startIndex into consideration)
if( index == numbers.length - 1) {
return (numbers[index] % 3 == 0 ? numbers[index] : 0);
}
// now, on to regular operations
// all that's needed is to return the current element, or zero, plus the recursive result
return (numbers[index] % 3 == 0 ? numbers[index] : 0) + computeSumDivisibleBy3( numbers, ++index );
// or, if you'd prefer an if statement
int cur = 0;
if( current element % 3 is 0 ) {
cur = current element
}
return cur + recurse( numbers, ++index );
//else{
// int sum1 = computeSumDivisibleBy3(numbers, startIndex, endIndex-1);
// if (numbers[endIndex] % 3 == 0)
// return sum1 + numbers[endIndex];
// else
//return sum1;
}
}