How to add a number to its own index [closed]
I will have a number which was taken as input from the use or i am storing a number assigned to a string as
string s"1234567";
As for this the index of each string will be as 0,1,2,3,4 and so on
I would like to add the number with that index as 1+0, 2+1 , 3+2 and so on like that
so that the output should be 1,3,5 like that
string s = string.Join(",", valueString.Select(
(c, i) => (i + (int)(c-'0')) % 10));
or in 2.0:
string[] result = new string[valueString.Length];
for(int i = 0; i < result.Length ; i++) result[i] =
((i + (int)(valueString[i] - '0')) % 10).ToString();
string s = string.Join(",", result);
IEnumerable<int> IndexDigitSum(string s)
{
for(int i=0;i<s.Length;i++)
{
int digit=s[i]-'0';
if(digit<0||digit>9)
throw new FormatException("Invalid Digit "+s[i]);
yield return (digit+i)%10;
}
}
In .net 2.0 you can replace yield return by adding to a local array:
int[] IndexDigitSum(string s)
{
int[] result=new int[s.Length];
for(int i=0;i<s.Length;i++)
{
int digit=s[i]-'0';
if(digit<0||digit>9)
throw new FormatException("Invalid Digit "+s[i]);
result[i]=(digit+i)%10;
}
return result;
}
Or if you want them concated:
string IndexDigitSum(string s)
{
string[] parts=new string[s.Length];
for(int i=0;i<s.Length;i++)
{
int digit=s[i]-'0';
if(digit<0||digit>9)
throw new FormatException("Invalid Digit "+s[i]);
parts[i]=((digit+i)%10).ToString();
}
return string.Join(",", parts);
}
To get the last digit of the sum one can simply add a %10 because the last digit of a number is it's remainder modulo 10.
精彩评论