开发者

How to add a number to its own index [closed]

开发者 https://www.devze.com 2023-01-22 11:37 出处:网络
It's difficult to tell what is being as开发者_JS百科ked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. F
It's difficult to tell what is being as开发者_JS百科ked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消