I have a large number like:
1012223457
I need to set the 3rd-most-significant digit in this number to 3
. How can I achieve that? Is there any way to do it without converting to string and without adding "20000000" to it?
I have a large number like:
1012223457
I need to set the 3rd-most-significant digit in this number to 3
. How can I achieve that? Is there any way to do it without converting to string and without adding "20000000" to it?
This would do it without a string. Most of the convolution is determining the length of the number without using string. So rather I use a mathematical trick:
long number = 1012223457;
number += (long)(2*Math.Pow(10.0,(double)((int)(Math.Log10(Math.Max(Math.Abs(number), 0.5)) + 1)-3)));
The 2*
is the value you wanted to add.
The solution is fugly, but it should work.
I didn't even think that the trick for the length of a number would be in StackOverflow but you can find information on it here . Coincidentally the code provided was in C#.
So one has to go with a pretty complex method without using strings, but would require math functions to compensate. I'd probably go with something that uses string
because readability would be much improved.
This is not the best way to do what you asked for OP, you have to use ToString for the best and most reliable solution, but nevertheless, here's a sample that does what you asked for:
var a = 10000000L;
var pows = Enumerable.Range(0, 16).Select(x => (long)Math.Pow(10, x));
var d = pows.First(x => a / x == 0);
var thirdDigit = (a / (d / 1000)) % 100;
a += (long)((3 - thirdDigit) * (d / 1000));
See this answer:
How can I get a count of the total number of digits in a number?
Thus it is posssible to do like this:
int digitpos = 5;
long number = 1080511231123;
int numbertoset = 3;
int digitcount = (int)Math.Floor(Math.Log10(number) + 1);
long exp = (long)Math.Pow(10, digitcount - digitpos);
if (exp == 0) throw new ArgumentException("The number does not contain required digit.");
int targetdigit = (int)(number / exp) % 10;
int multiplier = numbertoset - targetdigit;
long result = number + multiplier * exp;
To replace the target digit I had to calculate its value first.
The small usage of ToString results in a much cleaner code. Keep in mind that I am still using mathematical functions to do the change, no string manipulation involved.
var number = 123456789;
var length = number.ToString().Length;
var multiplier = Math.Pow(10, length - 3):
var oldDigit = Math.Floor(number / multiplier) % 10;
var change = 3 - oldDigit;
number += change * multiplier;