Brian H.
Brian H.

Reputation: 1677

Subtract 1 digit integer

I'm trying to write an algorithm program that has a step which involves subtracting a 1 digit integer by 1.

Which means: 3 -> 2, 5 -> 4, 0 -> 9, etc.

My current code is:

int subtractByOne(int val) {
    val = val - 1;
    return (val == -1) ? 9 : val;
}

So my point is, is there any operation or formula that will change 0 -> 9, and other cases like usual without an if branch statement?

I'm thinking about bit manipulation but I can barely find it. :(

Upvotes: 0

Views: 1343

Answers (4)

Falk Hüffner
Falk Hüffner

Reputation: 5040

If you want to avoid modulo, you can do the following:

int subtractByOne(int val) {
    val = val - 1;
    return val + ((val >> 31) & 10);
}

val >> 31 will be zero unless val is negative, when it is all ones, so the correction term will only be applied when the original val was 0.

Upvotes: 1

sarwadnya deshpande
sarwadnya deshpande

Reputation: 119

You can use following

Math.abs(~val<<3)+1

but it has limitations its useful when you want to change to 9 only if you want further you can change bits.

Upvotes: 0

shmosel
shmosel

Reputation: 50746

You can use a mod:

return (val + 9) % 10;

Upvotes: 4

freqnseverity
freqnseverity

Reputation: 136

Consider

int subtractByOne(int val) {
    return (val - 1) % 10;
}

The modulo function should return what you are looking for.

Upvotes: 0

Related Questions