c# - int to char array -
static void main(string[] args) { int num = 382; int output = 0; char[] nlst = num.tostring().tochararray(); (int = 0; < nlst.length; i++) { output += nlst[i]; } console.writeline(output); console.readline(); }
the output result 157, should 13.with dedbugging found 3 elements of char[] nlst :
[0]51'3', [1]56'8', [2]50'2'
why? what's meaning of 51,56,50?
you're assuming char value of '0'
0. not; in fact utf16 value of '0'
48.
so adding utf16 values of characters '3'
, '8'
, '2'
, i.e. 51, 56 , 50.
note if aim add digits of integer, best approach avoid converting string completely, so:
int num = 382; // compute sum of digits of num int total = 0; while (num > 0) { total += num%10; num /= 10; } console.writeline(total);
however if want know how version working, subtract '0'
each character before adding codes together. convert '0'
0, '1'
1, etc:
for (int = 0; < nlst.length; i++) { output += nlst[i] - '0'; // subtract '0' here. }
Comments
Post a Comment