How to multiply decimal numbers without using multiplication(*) sign - c#

Can anyone suggest me a way to multiply decimal numbers without using multiplication(*) sign.
I know it looks like homework thing, but I just want to know how to achieve this. I have already done this for positive and negative integers as below:
int first = 2;
int second =2;
int result = 0;
bool isNegative = false;
if (first < 0)
{
first = Math.Abs(first);
isNegative = true;
}
if (second < 0)
{
second = Math.Abs(second);
isNegative = true;
}
for (int i = 1; i <= second; i++)
{
result += first;
}
if (isNegative)
result = -Math.Abs(result);
Want to multiply this for decimals:
decimal third = 1.1;
decimal fourth = 1.2;
Thanks

Bit of a cheat, but if the task strictly relates to all forms of multiplication (rather than just the * operator), then divide by the reciprocal:
var result = first / (1 / (decimal)second);

Just another way ;)
if (second < 0)
{
second = Math.Abs(second);
first = (-1) * first;
}
result = Enumerable.Repeat(first, second).Sum();

The simplest way to multiple two decimals without using the * operator is to use the Decimal.Multiply method.
Example:
decimal first = -2.234M;
decimal second = 3.14M;
decimal product = Decimal.Multiply(first, second);

Strictly with out '*' ? I'd take note of the XOR operator implemented. Although I know this code is not much different to the OP's.
int first = 2;
int second =2;
int result = 0;
bool isNegative;
isNegative = (first<0)^(second<0);
first = (first<0)?Math.Abs(first):first;
second = (second<0)?Math.Abs(second):second;
for (int i = 1; i <= second; i++)
result += first;
result = (isNegative)?-Math.Abs(result):result;

Here's another approach, using rules of logs, for the sake of completeness:
decimal result = (decimal)Math.Exp(
Math.Log((double)third) + Math.Log((double)fourth));
It's not going to work for all decimals (in particular not for negative numbers, although it could be extended to detect these and work around them), but it's interesting nevertheless.

Related

C# method for solving missing exponent

With the equation X^Y = Z, how can I write a c# method, to solve for Y?
Does one already exist?
Here are some examples of the data I will have -
2^Y = 8
3^Y = 9
Try this
Y=Math.Log(8) / Math.Log(2)
You're looking for Math.Log.
With that you can do:
x = Math.Log(8) / Math.Log(2)
Also not that there is a Math.Log10 which is the logarithm by base 10 - the outcome is yet the same.
Not the most optimized option but you can iterate through a for-loop of huge amount of numbers, and check one by one iteratively. Just a solution that popped up in my head. Code would look something like:
int base = 2;
int exponent;
int result = 8;
for(int i = -9999; i<= 10000000; i++)
{
exponent = i;
if(Math.Pow(2,exponent) == result)
{
WriteLine($"Y = {exponent}");
}
You can find out how many time Z can be devided by X.
Hope this helps.
while (Z > X)
{
Z = Z / X;
Y++;
}

Get number of digits before decimal point

I have a variable of decimal type and I want to check the number of digits before decimal point in it.
What should I do? For example, 467.45 should return 3.
Solution without converting to string (which can be dangerous in case of exotic cultures):
static int GetNumberOfDigits(decimal d)
{
decimal abs = Math.Abs(d);
return abs < 1 ? 0 : (int)(Math.Log10(decimal.ToDouble(abs)) + 1);
}
Note, that this solution is valid for all decimal values
UPDATE
In fact this solution does not work with some big values, for example: 999999999999998, 999999999999999, 9999999999999939...
Obviously, the mathematical operations with double are not accurate enough for this task.
While searching wrong values I tend to use string-based alternatives proposed in this topic. As for me, that is the evidence that they are more reliable and easy-to-use (but be aware of cultures). Loop-based solutions can be faster though.
Thanks to commentators, shame on me, lesson to you.
Instead of converting to string, you can also divide the number by 10 until it equals 0. Interesting is, that the mathematical operations on decimals are much slower than converting the decimal to a string and returning the length (see benchmarks below).
This solution does not use the Math-methods that take a double as input; so all operations are done on decimals and no casting is involved.
using System;
public class Test
{
public static void Main()
{
decimal dec = -12345678912345678912345678912.456m;
int digits = GetDigits(dec);
Console.WriteLine(digits.ToString());
}
static int GetDigits(decimal dec)
{
decimal d = decimal.Floor(dec < 0 ? decimal.Negate(dec) : dec);
// As stated in the comments of the question,
// 0.xyz should return 0, therefore a special case
if (d == 0m)
return 0;
int cnt = 1;
while ((d = decimal.Floor(d / 10m)) != 0m)
cnt++;
return cnt;
}
}
Output is 29. To run this sample, visit this link.
Side note: some benchmarks show surprising results (10k runs):
while ((d = decimal.Floor(d / 10m)) != 0m): 25ms
while ((d = d / 10m) > 1m): 32ms
ToString with Math-double-operations: 3ms
ToString with decimal-operations: 3ms
BigInt (see answer of #Heinzi): 2ms
Also using random numbers instead of always the same value (to avoid possible caching of the decimal to string conversion) showed that the string-based methods are much faster.
I would try this:
Math.Truncate(467.45).ToString().Length
If you want to be sure not having some weird results for different cultures and with negative decimals, you better use this:
var myDecimal = 467.45m;
Math.Truncate(Math.Abs(myDecimal)).ToString(CultureInfo.InvariantCulture).Length
I would prefer the following instead of casting to int to ensure that you can also handle big numbers (e.g. decimal.MaxValue):
Math.Truncate ( Math.Abs ( decValue ) ).ToString( "####" ).Length
decimal d = 467.45M;
int i = (int)d;
Console.WriteLine(i.ToString(CultureInfo.InvariantCulture).Length); //3
As a method;
public static int GetDigitsLength(decimal d)
{
int i = int(d);
return i.ToString(CultureInfo.InvariantCulture).Length;
}
Note: Of course you should check first your decimals full part is bigger than Int32.MaxValue or not. Because if it is, you get an OverflowException.
Is such a case, using long instead of int can a better approach. However even a long (System.Int64) is not big enough to hold every possible decimal value.
As Rawling mentioned, your full part can hold the thousands separator and my code will be broken in such a case. Because in this way, it totally ignores my number contains NumberFormatInfo.NumberGroupSeparator or not.
That's why getting numbers only is a better approach. Like;
i.ToString().Where(c => Char.IsDigit(c)).ToArray()
Here's a recursive example (mostly for fun).
void Main()
{
digitCount(0.123M); //0
digitCount(493854289.543354345M); //10
digitCount(4937854345454545435549.543354345M); //22
digitCount(-4937854345454545435549.543354345M); //22
digitCount(1.0M); //1
//approximately the biggest number you can pass to the function that works.
digitCount(Decimal.MaxValue + 0.4999999M); //29
}
int digitCount(decimal num, int count = 0)
{
//divided down to last digit, return how many times that happened
if(Math.Abs(num) < 1)
return count;
return digitCount(num/10, ++count); //increment the count and divide by 10 to 'remove' a digit
}
Math.Floor(Math.Log10((double)n) + 1); is the way to go.
Converting to int is BAD because decimal may be bigger than int:
Decimal.MaxValue = 79,228,162,514,264,337,593,543,950,335;
Int32.MaxValue = 2,147,483,647; //that is, hexadecimal 0x7FFFFFFF;
Math.Floor(n).ToString().Count(); is bad because it may include thousands seperators.
If you have a bias towards smaller numbers, you can use something more simple like this.
It is split up into two methods, so the first method is smaller and can be inlined.
Performance is about the same as the solution with the Log10, but without the rounding errors. The Method using Log10, is still the fastest (a bit) specially for numbers > 1 million.
public static int CountNrOfDigitsIfs(decimal d) {
var absD = Math.Abs(d);
// 1
if (absD < 10M) return 1;
// 2
if (absD < 100M) return 2;
// 3
if (absD < 1000M) return 3;
// 4
if (absD < 10000M) return 4;
return CountNrOfDigitsIfsLarge(d);
}
private static int CountNrOfDigitsIfsLarge(decimal d) {
// 5
if (d < 100000M) return 5;
// 6
if (d < 1000000M) return 6;
// 7
if (d < 10000000M) return 7;
// 8
if (d < 100000000M) return 8;
// 9
if (d < 1000000000M) return 9;
// 10
if (d < 10000000000M) return 10;
// 11
if (d < 100000000000M) return 11;
// 12
if (d < 1000000000000M) return 12;
// 13
if (d < 10000000000000M) return 13;
// 14
if (d < 100000000000000M) return 14;
// 15
if (d < 1000000000000000M) return 15;
// 16
if (d < 10000000000000000M) return 16;
// 17
if (d < 100000000000000000M) return 17;
// 18
if (d < 1000000000000000000M) return 18;
// 19
if (d < 10000000000000000000M) return 19;
// 20
if (d < 100000000000000000000M) return 20;
// 21
if (d < 1000000000000000000000M) return 21;
// 22
if (d < 10000000000000000000000M) return 22;
// 23
if (d < 100000000000000000000000M) return 23;
// 24
if (d < 1000000000000000000000000M) return 24;
// 25
if (d < 10000000000000000000000000M) return 25;
// 26
if (d < 100000000000000000000000000M) return 26;
// 27
if (d < 1000000000000000000000000000M) return 27;
// 28
if (d < 10000000000000000000000000000M) return 28;
return 29; // Max nr of digits in decimal
}
This code is generated using the following T4 template:
<#
const int SIGNIFICANT_DECIMALS = 29;
const int SPLIT = 5;
#>
namespace Study.NrOfDigits {
static partial class DigitCounter {
public static int CountNrOfDigitsIfs(decimal d) {
var absD = Math.Abs(d);
<#
for (int i = 1; i < SPLIT; i++) { // Only 29 significant digits
var zeroes = new String('0', i);
#>
// <#= i #>
if (absD < 1<#= zeroes #>M) return <#= i #>;
<#
}
#>
return CountNrOfDigitsIfsLarge(d);
}
private static int CountNrOfDigitsIfsLarge(decimal d) {
<#
for (int i = SPLIT; i < SIGNIFICANT_DECIMALS; i++) { // Only 29 significant digits
var zeroes = new String('0', i);
#>
// <#= i #>
if (d < 1<#= zeroes #>M) return <#= i #>;
<#
}
#>
return <#= SIGNIFICANT_DECIMALS #>; // Max nr of digits in decimal
}
}
}
So, I've run into this before, and solved it with this code:
SqlDecimal d = new SqlDecimal(467.45M);
int digits = d.Precision - d.Scale;
SqlDecimal is part of the System.Data.SqlTypes namespace. "Precision" is the total number of significant digits, while "Scale" is the number of digits after the decimal point.
Now, I know one objection to going this route is that SqlDecimal is part of the SQL Server-specific code. It's a valid point, but I would also point out that it's a part of the .NET framework itself, and has been since at least version 1.1, so it seems like it would be still be applicable no matter what the code around it is doing.
I looked under the hood with a decompiler (JetBrains' dotPeek in this instance), to see if maybe the code for calculating precision and scale could be easily extracted and just used, without pulling in SqlDecimal. The code to calculate scale is very simple, but the method to calculate precision is non-trivial, so if it were me, I'd just go through SqlDecimal.
This will do if you really don't want to use the Log method (which IMO is the best way). It's about the clearest way I can think of of doing this using ToString():
Math.Abs(val).ToString("f0", CultureInfo.InvariantCulture).Length
Or alternatively, if you don't want to count 0.123M as having one digit:
Math.Abs(val).ToString("#", CultureInfo.InvariantCulture).Length
You could use ToString function with a custom format.
Decimal value = 467.45m;
int count = Math.Abs(value).ToString("#", System.Globalization.CultureInfo.InvariantCulture).Length;
The # specify you only want the characters before the .
The System.Globalization.CultureInfo.InvariantCulture ensure you won't get any formating from the Region Option.
This answer is pretty much lifted from Calculate System.Decimal Precision and Scale but with a minor change to fit the question asked.
class Program
{
static void Main()
{
decimal dec = 467.45m;
Console.WriteLine(dec.GetNumberOfDigitsBeforeDecimalPlace());
}
}
public static class DecimalEx
{
public static int GetNumberOfDigitsBeforeDecimalPlace(this decimal dec)
{
var x = new System.Data.SqlTypes.SqlDecimal(dec);
return x.Precision - x.Scale;
}
}
Also if you want to do it without using the SqlDecimal class check out Jon Skeet's answer for the same question.
var sep = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
var count = d.ToString().TakeWhile(c => c != sep).Count();
The mathematical way of doing this (and probably the fastest) is to get a logarytm of base 10 of a absolute value of this number and round it
up.
Math.Floor(Math.Log10(Math.Abs(val)) + 1);
TLDR all the other answers. I wrote this in PHP, and the math would be the same. (If I knew C# I'd have written in that language.)
$input=21689584.999;
$input=abs($input);
$exp=0;
do{
$test=pow(10,$exp);
if($test > $input){
$digits=$exp;
}
if($test == $input){
$digits=$exp+1;
}
$exp++;
}while(!$digits);
if($input < 1){$digits=0;}
echo $digits;
I don't doubt there's a better way, but I wanted to throw in my $.02
EDIT:
I php-ized the code I mentioned in my comments, but did away with the int conversion.
function digitCount($input){
$digits=0;
$input=abs($input);
while ($input >= 1) {
$digits++;
$input=$input/10;
//echo $input."<br>";
}
return $digits;
}
$big=(float)(PHP_INT_MAX * 1.1);
echo digitCount($big);
Use modulo, i'm not a C# programmer, but I'm pretty sure this solution work:
double i = 1;
int numberOfDecimals = 0;
while (varDouble % i != varDouble)
{
numberOfDecimals++;
i*=10;
}
return numberOfDecimals;
This would be the Java solution
public class test {
public static void main(String args[]) {
float f = 1.123f;
int a = (int) f;
int digits = 0;
while (a > 0) {
digits++;
a=a/10;
}
System.out.println("No Of digits before decimal="+digits);
}
}
If you treat zeros or lack of zeroes as 1 number, this is OK. If you want zero to return zero or lack of zero to return zero, then there are a few edge cases to work out which shouldn't be too hard to add. Also, should Absolute value to handle negative numbers. Added that test case as well.
const decimal d = 123.45m;
const decimal d1 = 0.123m;
const decimal d2 = .567m;
const decimal d3 = .333m;
const decimal d4 = -123.45m;
NumberFormatInfo currentProvider = NumberFormatInfo.InvariantInfo;
var newProvider = (NumberFormatInfo) currentProvider.Clone();
newProvider.NumberDecimalDigits = 0;
string number = d.ToString("N", newProvider); //returns 123 = .Length = 3
string number1 = d1.ToString("N", newProvider); //returns 0 = .Length = 1
string number2 = d2.ToString("N", newProvider); //returns 1 = .Length = 1
string number3 = d3.ToString("N", newProvider); //returns 0 = .Length = 1
string number4 = Math.Abs(d4).ToString("N", newProvider); //returns 123 = .Length = 3
Here's a somewhat final solution, if you find a test case that doesn't work, let me know. It should return 3,0,0,0,3 for the test cases provided.
public static int NumbersInFrontOfDecimal(decimal input)
{
NumberFormatInfo currentProvider = NumberFormatInfo.InvariantInfo;
var newProvider = (NumberFormatInfo)currentProvider.Clone();
newProvider.NumberDecimalDigits = 0;
var absInput = Math.Abs(input);
var numbers = absInput.ToString("N", newProvider);
//Handle Zero and < 1
if (numbers.Length == 1 && input < 1.0m)
{
return 0;
}
return numbers.Length;
}
Here is my optimized version of the code inspired by Gray's answer:
static int GetNumOfDigits(decimal dTest)
{
int nAnswer = 0;
dTest = Math.Abs(dTest);
//For loop version
for (nAnswer = 0; nAnswer < 29 && dTest > 1; ++nAnswer)
{
dTest *= 0.1M;
}
//While loop version
//while (dTest > 1)
//{
// nAnswer++;
// dTest *= 0.1M;
//}
return (nAnswer);
}
If you don't want the Math.Abs to be called inside this function then be sure to use it
outside the function on the parameter before calling GetNumOfDigits.
I decided to remove the other codes to reduce clutter in my answer, even though they helped me get to this point...
If there is any improvements needed, then let me know and I will update it :).
In order to get an accurate and culturally agnostic answer I do the following:
Use System.Numerics.BigInteger, whose constructor accepts a decimal and doesn't seem to produce any rounding errors.
Use BigInteger.Abs() to remove any sign.
Use BigInteger.ToString() with the "#" format to suppress any separators that might occur.
Code
decimal num = 123213123.123123M;
int length = BigInteger.Abs((BigInteger)num).ToString("#").Length;
You could do this by rounding the number, then getting the length of the new number. You could do it like this:
var number = 476.43;
var newNumber = Math.round(number);
//get the length of the rounded number, and subtract 1 if the
//number is negative (remove the negative sign from the count)
int digits = newNumber.ToString().Length - (number < 0 ? 1 : 0);
The other solutions will lose digits if the number is too large.
public int Digits(Decimal i)
{
NumberFormatInfo format = CultureInfo.CurrentCulture.NumberFormat;
var str = Math.Abs(i).ToString().Replace(format.NumberGroupSeparator, "");
var index = str.IndexOf(format.NumberDecimalSeparator);
var digits = index == -1 ? str.Length : index;
}
Algorithm:
Convert |decimal| to String.
If "." exist in the decimal, cut before it, otherwise consider the whole number.
Return string length.
Example:
3.14 --> 3.14 --> "3.14" --> "3.14".Substring(0,1) --> "3".Length --> 1
-1024 --> 1024 --> "1024" --> IndexOf(".") = -1 --> "1024" --> 4
Code:
static int getNumOfDigits (decimal num)
{
string d = Math.Abs(num).ToString();
if (d.IndexOf(".") > -1)
{
d = d.Substring(0, d.IndexOf("."));
}
return d.Length;
}
I haven't tested this but I would keep it straightforward and do:
decimal value = 467.45;
string str = Convert.toString(value); // convert your decimal type to a string
string[] splitStr = str.split('.'); // split it into an array (use comma separator assuming you know your cultural context)
Console.WriteLine(splitStr[0].Count); // get the first element. You can also get the number of figures after the point by indexing the next value in the array.
This does not handle negative numbers. If you care about those then considering taking the absolute value. Furthermore, if you want 0 before the decimal place to not be counted then you can use a simple if statement to check it.
simple :
string value = "467.45";
int count = value.split('.')[0] == "0" ? 0 : value.split('.')[0].ToString().Replace("-","").Count();

Limit exponent only to specific powers

In our program we have values around millions to milliards which need to be displayed. Due to user requirements, the users want to see only exponent values which are dividable by 3. means the values to be displayed shall be like
1e0
10e0
100e0
1e3
10e3
100e3
1e6
and so on. I want to change exponent where thousands are encountered, to simplify the user the way to distinguish kilobits, megabits, gigabits.
Is it possible to get this effect with a format string?
Something like this
int val = 123456789;
var order = (int)Math.Log10(val);
var auxOrder = order/3;
var charToShow = val.ToString().Length - (auxOrder *3);
var result = val.ToString().Substring(0, charToShow )+"e"+(auxOrder *3);
There are better names for the variables like mantissa e exponent, but it will do the trick
The code from Servy was the starting point, but it still had some bugs, not working for negative or very small values. I expanded it like this
double exponent = Math.Log10(Math.Abs(val));
var negcompensator = 0;
if (exponent < 0)
{
negcompensator = -1;
}
int displayExponent = (int)(Math.Truncate((exponent + negcompensator) / 3)) * 3;
if (displayExponent==0 || double.IsInfinity(exponent))
{
return val.ToString("###0.##");
}
else
{
var displayValue = (val / Math.Pow(10, displayExponent));
return string.Format("{0}e{1}", displayValue, displayExponent);
}
I dislike solutions like this that involve string manipulation, so I calculated both portions mathematically here.
public static string MyFormat(int value)
{
double exponent = Math.Log10(value);
int displayExponent = (int)(exponent / 3);
int displayValue = (int)(value / Math.Pow(exponent, 10));
return string.Format("{0}e{1}", displayValue, displayExponent);
}

Convert hexadecimal to decimal

I'm currently building a converter in C#. My program is converting from/to Decimal, Binary and Hexadecimal. My problem is that in some specific cases the result is not correct.
Examples:
FFFFF (hexa) to Decimal = 148575 (Real answer: 1048575)
20000 (decimal) to Decimal = 20 (Real answer: dont need a calculator :P)
Also I can't use any Convert.ToString as it is for school and my teacher asked us to manipulate the variables and play with functions.
I think my convertToString() function causes the problem of losing zeros somewhere.
private string convertToString(int value)
{
string result = "";
string tmp = "";
int y = 0;
while (value != 0) {
int valeur = value;
y = 0;
while (valeur > 9) {
valeur = valeur / 10;
y++;
}
switch (valeur) {
case 0:
tmp = "0";
break;
case 1:
tmp = "1";
break;
case 2:
tmp = "2";
break;
case 3:
tmp = "3";
break;
case 4:
tmp = "4";
break;
case 5:
tmp = "5";
break;
case 6:
tmp = "6";
break;
case 7:
tmp = "7";
break;
case 8:
tmp = "8";
break;
case 9:
tmp = "9";
break;
}
value = (int)(value - (valeur * Math.Pow(10, y)));
result = result + tmp;
}
if (y != 0) {
result = result + "0";
}
return result;
}
Thank you in advance.
I would advise you to step through your code in the debugger, examining the flow of control. You should also examine values of the variables using the Locals window. You will see where the algorithm you created is different from the algorithm you thought you created.
Another useful technique is to break the existing method into smaller methods that perform simpler parts of the task. Give the methods names that describe the part of the task they're doing. This makes it easier to change your logic (for example, when you learn about a better way to convert digits to characters!). Good luck.
Take a simple number like value=123 or value=103 and execute the code step by step.
You can do this using debugger single stepping and watching the values of the variables, but if you want to really learn how the code works, use your own brain as the CPU and see if you can work through it on a piece of paper.
As you step through the operations you will be able to see what happens to the numbers and can watch the exact moment wheer it goes wrong, in order to come to an understanding of what is happening.
The problem is that you create confusion with two names meaning the same in English and French: value / valeur;
You would calculate the decimal places like this
string result = "";
bool minus = false;
if (value == 0 ) {
result = "0";
} else {
// Begin the string with a minus (`-`) if value is negative
// and continue the conversion with a positive value.
if (value < 0) {
minus = true;
value = - value;
}
// Add decimals to the result as long as the remaining number is not zero.
while (value > 0) {
// Get last decimal using the modulo operator
int lastDecimal = value % 10;
// Prepend the decimal to the result after having converted it to a character
result = (char)('0' + lastDecimal) + result;
// Divide the value by 10. Integer division!
value = value / 10;
}
if (minus) {
result = "-" + result;
}
}
It looses 0's here:
while (valeur > 9)
{
valeur = valeur / 10;
y++;
}
You keep dividing the number until its less than 9, incrementing the count using the variable y.
Then you cant get it back using this:
value = (int)(value - (valeur * Math.Pow(10, y)));
I dont know what the point of this function is, I'm guessing ToString without using the inbuilt function, if so here is one way using a StringBuilder and Int Array:
private string convertToString(int value)
{
int[] valueAsArray = digitArr(value);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < valueAsArray.Length; i++)
{
sb.Append(valueAsArray[i]);
}
return sb.ToString();
}
public static int[] digitArr(int n)
{
if (n == 0) return new int[1] { 0 };
var digits = new List<int>();
for (; n != 0; n /= 10)
{
digits.Add(n%10);
}
var arr = digits.ToArray();
Array.Reverse(arr);
return arr;
}
I would urge you to fix your own function that way when your teacher checks here he see's you put in effort and worked it out using the debugger as phong mentioned...
This is a good example of when you have one known good function, and you want to test your own implementation against it. How might this code:
for (int i = 0; i < 100000; i++)
{
if (i.ToString() != ConvertToString(i))
{
Console.WriteLine(i);
ConvertToString(i);
}
}
help you? First of all, it will tell you which numbers your method doesn't work for. Second, you can attach the debugger to the WriteLine line, and then step through the second run through of your method.
Here's an example that works using Math.Log10 and Math.Pow. Step through it with the debugger to see why it doesn't drop any zeros (it did at first, but it was obvious why after using the seeing which cases is failed for, then using the debugger).
static string ConvertToString(int value)
{
string result = "";
int power = (int)Math.Log10(value);
while (power >= 0)
{
int nextLowestPowerOfTen = (int)Math.Pow(10, power);
int lowestMultipleOfPowerOfTen = (int)(value / nextLowestPowerOfTen);
result += lowestMultipleOfPowerOfTen;
value -= lowestMultipleOfPowerOfTen * nextLowestPowerOfTen;
power--;
}
return result;
}

Need code for addition of 2 numbers

I am having the numbers follows taken as strings
My actual number is 1234567890123456789
from this i have to separate it as s=12 s1=6789 s3=3456789012345
remaining as i said
I would like to add as follows
11+3, 2+4, 6+5, 7+6, 8+7, 9+8 such that the output should be as follows
4613579012345
Any help please
public static string CombineNumbers(string number1, string number2)
{
int length = number1.Length > number2.Length ? number1.Length : number2.Length;
string returnValue = string.Empty;
for (int i = 0; i < length; i++)
{
int n1 = i >= number1.Length ? 0 : int.Parse(number1.Substring(i,1));
int n2 = i >= number2.Length ? 0 : int.Parse(number2.Substring(i,1));
int sum = n1 + n2;
returnValue += sum < 10 ? sum : sum - 10;
}
return returnValue;
}
This sounds an awful lot like a homework problem, so I'm not giving code. Just think about what you need to do. You are saying that you need to take the first character off the front of two strings, parse them to ints, and add them together. Finally, take the result of the addition and append them to the end of a new string. If you write code that follows that path, it should work out fine.
EDIT: As Ralph pointed out, you'll also need to check for overflows. I didn't notice that when I started typing. Although, that shouldn't be too hard, since you're starting with a two one digit numbers. If the number is greater than 9, then you can just subtract 10 to bring it down to the proper one digit number.
How about this LINQish solution:
private string SumIt(string first, string second)
{
IEnumerable<char> left = first;
IEnumerable<char> right = second;
var sb = new StringBuilder();
var query = left.Zip(right, (l, r) => new { Left = l, Right = r })
.Select(chars => new { Left = int.Parse(chars.Left.ToString()),
Right = int.Parse(chars.Right.ToString()) })
.Select(numbers => (numbers.Left + numbers.Right) % 10);
foreach (var number in query)
{
sb.Append(number);
}
return sb.ToString();
}
Tried something:
public static string NumAdd(int iOne, int iTwo)
{
char[] strOne = iOne.ToString().ToCharArray();
char[] strTwo = iTwo.ToString().ToCharArray();
string strReturn = string.Empty;
for (int i = 0; i < strOne.Length; i++)
{
int iFirst = 0;
if (int.TryParse(strOne[i].ToString(), out iFirst))
{
int iSecond = 0;
if (int.TryParse(strTwo[i].ToString(), out iSecond))
{
strReturn += ((int)(iFirst + iSecond)).ToString();
}
}
// last one, add the remaining string
if (i + 1 == strOne.Length)
{
strReturn += iTwo.ToString().Substring(i+1);
break;
}
}
return strReturn;
}
You should call it like this:
string strBla = NumAdd(12345, 123456789);
This function works only if the first number is smaller than the second one. But this will help you to know how it is about.
In other words, you want to add two numbers treating the lesser number like it had zeroes to its right until it had the same amount of digits as the greater number.
Sounds like the problem at this point is simply a matter of finding out how much you need to multiply the smaller number by in order to reach the number of digits of the larger number.

Categories