Reputation: 23
I am trying to find the weighted sum of digits for example if I have 124 I need to make it: 1 * 1 + 2 * 2 + 4 * 3.
So far I have been able to multiply the numbers using a for loop like so:
Console.WriteLine("Input a number");
int num = Convert.ToInt32(Console.ReadLine());
int digit = 0;
for (int i = 4; i > 0; i--)
{
digit = num % 10 * i;
num /= 10;
Console.WriteLine(digit);
}
But I'm unsure as to how to add the numbers after.
Upvotes: 0
Views: 1216
Reputation: 186668
If you are for simple solution (which is not very fast) you can try Linq:
Console.WriteLine("Input a number");
int num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(string.Join(" + ", num
.Select((c, i) => $"{c - '0'} * {i + 1}")););
Outcome:
1 * 1 + 2 * 2 + 4 * 3
If you want to find out the sum, add Sum
:
int sum = num
.Select((c, i) => (c - '0') * (i + 1))
.Sum();
Upvotes: 0
Reputation: 160
int num, sum = 0, r;
Console.WriteLine("Enter a Number : ");
num = int.Parse(Console.ReadLine());
var add_n=(num.ToString().Length)+1;
while (num != 0)
{
r = num % 10;
num = num / 10;
//Console.WriteLine(r+" "+(add_n-1));
sum = sum + (r*(add_n-1));
add_n--;
}
Console.WriteLine("Sum of Digits of the Number : "+sum);
Console.ReadLine();
Upvotes: 0
Reputation: 199
Are you trying to achieve this?
Console.WriteLine("Input a number");
int num = Convert.ToInt32(Console.ReadLine());
int digit = 0;
int i=num.ToString().Length;
int Sum= 0;
int digit2=0;
while(num>0)
{
digit= num%10;
digit2=digit*i;
Sum=Sum+digit2;
num=num/10;
i--;
}
Console.Writeline(Sum);
Upvotes: 1
Reputation: 1976
you can do this for 4 digits numbers
Console.WriteLine("Input a number");
int num = Convert.ToInt32(Console.ReadLine());
int sum = 0;
for (int i = 4; i > 0; i--)
{
sum += num % 10 * i;
num /= 10;
}
Console.WriteLine(sum);
but if you want your code work for any number, do this
Console.WriteLine("Input a number");
int num = Convert.ToInt32(Console.ReadLine());
int sum = 0;
for (int i = num.ToString().Length; i > 0; i--)
{
sum += num % 10 * i;
num /= 10;
}
Console.WriteLine(sum);
Upvotes: 1