1

I am trying to find most optimized formula for achieving following result.

For example, There is a number 125. I need to change its tenth which is '2' to '7', resulting 175.

One formula that I derived:

= 125 + {(7 - (125 / 10 % 10)} * 10
= 125 + (7 - 2) * 10
= 125 + 50
= 175

But, what if I have to change unit or hundred or x digit of a number?

Akshat
  • 165
  • Optimized how? For programming? For x86/x86_64 processor arithmetic? For Java implementation? For GCC 4.8? For JavaScript? – Asaf Karagila Jan 18 '14 at 21:52
  • Optimized for programming or even better idea or formula! – Akshat Jan 18 '14 at 21:53
  • If it's for "general" programming, then your idea is as optimized as they get because it's in $O(1)$, and you can't get better than that. In generally, this seems more like a question about programming than it is about mathematics, and I think that it might fit better on StackOverflow.com than this site. – Asaf Karagila Jan 18 '14 at 21:57
  • If you want to change the k-th digit from the right, just replace the $10$'s with $10^{k-1}$ (except for the % 10) – dani_s Jan 18 '14 at 22:00

2 Answers2

0

To replace digit D with digit Z in number x = ...Def (digit representing hundreds), one can use code

... = x - x%1000 + x%100 + Z*100;


To replace digit D with digit Z in number x = ...Defg (digit representing thousands), one can use code

    ... = x - x%10000 + x%1000 + Z*1000;

And so on.


(C/C++/Java code style).

Oleg567
  • 17,295
0

If you know that the $k$th digit (from the right) of the positive number $x$ is a $d$ and you want to change it to $d'$, just add $(d'-d)\cdot 10^{k-1}$ to $x$. If you don't know $d$ beforehand, you can find it as $d=\left\lfloor \frac x{10^{k-1}}\right\rfloor\bmod 10$. If you also have to deal with negative $x$, it is easiest to deal with $|x|$ and re-multiply with the sign of $x$ in the end.