-3

I have a problem. I give it string "BC" and it outputs 54 not 55 as in first cycle num = 3 and in second num = 52 but the sum is 54 why? Can you help me?

string getX(string x) {
    int ans = 0, num;
    for (int i = 0, j = x.size() - 1; i < x.size(), j >= 0; i++, j--) {
        num = x[j] - 64;
        num = num * pow(26, i);
        ans += num;
    }
    return to_string(ans);
}
Buglinjo
  • 2,067
  • 1
  • 15
  • 26
  • 4
    Off topic: `i <= x.size() - 1;` can be accomplished with `i < x.size();` – user4581301 Nov 21 '16 at 20:30
  • 2
    You don't need to cast `(int)num`, since `num` is already declared to be `int`. – Barmar Nov 21 '16 at 20:31
  • Yeah I know. I have done This too `for (int i = 0, j = x.size() - 1; i < x.size(), j >= 0; i++, j--)` – Buglinjo Nov 21 '16 at 20:31
  • 3
    `pow(26, i)` may give you a few surprises. `pow` returns `double` which may not be exact. – user4581301 Nov 21 '16 at 20:32
  • `pow` computes in floating point. The result could be approximated like `54.999999999`. When casted into `int` during `+=` operation, the result could be `54`. – Franck Nov 21 '16 at 20:32
  • This can probably be solved by calling `round()` on `pow`'s returned value. – MrPromethee Nov 21 '16 at 20:34
  • better write `num = x[j] - 'A' - 1;` if you don't know ASCII codes by heart – Jean-François Fabre Nov 21 '16 at 20:34
  • Prefer to use character constants, like `x[j] - 'A'`, rather than their ASCII decimal numbers. – Thomas Matthews Nov 21 '16 at 20:34
  • there's a good integer power function somewhere on SO: http://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int – Jean-François Fabre Nov 21 '16 at 20:35
  • @Franck While that's theoretically possible, does it really happen when both inputs are integers? I guess it would happen if the implementation uses logarithms to calculate it. – Barmar Nov 21 '16 at 20:36
  • @Barmar I agree. It shouldn't. I have not reproduced it. On my machine result is 55. `pow(26, 1)` should be 26: no approximation, but in theory it depends from the libc++. – Franck Nov 21 '16 at 20:38
  • I think your `i < x.size(), j >= 0` edit may have made things weirder. The comma operator will evaluate and discard `i < x.size()` and then use `j >= 0` as intended. – user4581301 Nov 21 '16 at 20:38
  • @user4581301 That's OK, because either of them is a valid test. – Barmar Nov 21 '16 at 20:42
  • @Barmar that's why I went with "weirder". It works, but it's weird. – user4581301 Nov 21 '16 at 20:43

2 Answers2

1

You don't need the pow function. Multipy by 26, then add:

unsigned int num = 0U;
for (j = 0; j < x.size(); ++j)
{
  num = num * 26;
  num += (x[j] - 'A');
}
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
0

round(pow(26,i)) Helped. Thank you @MrPromethee

Buglinjo
  • 2,067
  • 1
  • 15
  • 26