0

I made this method for an assignment in class. To count the number of '1's appearing in any given number. I would like to expand on this and learn how to take a number and if it is even number adds one to it. If it is an odd number subtract one from it using recursion and return that changed number.

public static int countOnes(int n){
    if(n < 0){
        return countOnes(n*-1);
    }
    if(n == 0){
        return 0;
    }
    if(n%10 == 1){
        return 1 + countOnes(n/10);
    }else 
        return countOnes(n/10);
}

0 would = 1 27 would = 36 so on. I would appreciate any help that is given.

5
  • 2
    It's not clear what's the problem with the code you posted. Commented May 1, 2019 at 6:59
  • 1
    9 would be 8 @AndyTurner Commented May 1, 2019 at 7:04
  • There's no issue with the code that I posted I was just giving some reference as to why I decided to try and do what I am trying to do. @Eran Commented May 1, 2019 at 7:06
  • How is the number of 1s 36 in the number 27? I don't get it at all. Your description doesn't match the code at all. There's no odd-check in the code, only a '= 1 mod 10' check. Commented May 1, 2019 at 7:17
  • @MarkJeronimus the code is misleading. It has nothing to do with the problem OP is asking about, other than OP wrote it, it is recursive and OP is asking how to solve the problem recursively. Commented May 1, 2019 at 7:23

1 Answer 1

1

You quite often find that using private method in a recursive solution makes your code much clearer.

/**
 * Twiddles one digit.
 */
private static int twiddleDigit(int n) {
    return (n & 1) == 1 ? n - 1 : n + 1;
}

/**
 * Adds one to digits that are even, subtracts one from digits that are odd.
 */
public static int twiddleDigits(int n) {
    if (n < 10) return twiddleDigit(n);
    return twiddleDigits(n / 10) * 10 + twiddleDigit(n % 10);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.