Advertisement
JavaFan

Add Positive Integer Numbers

Jan 2nd, 2014
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.91 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Numerics;
  7.  
  8. namespace _08.AddNumbers
  9. {
  10. class Program
  11. {
  12. // Write a method that adds two positive integer numbers represented as arrays of digits
  13. // (each array element arr[i] contains a digit; the last digit is kept in arr[0]).
  14. // Each of the numbers that will be added could have up to 10 000 digits.
  15.  
  16. static BigInteger addArraysOfDigits(int[] arr1, int[] arr2)
  17. {
  18. int maxLen = arr1.Length > arr2.Length ? arr1.Length:arr2.Length;
  19.  
  20. int[] tempArr = new int[maxLen + 1];
  21. int[] sum = new int[maxLen + 1];
  22.  
  23. if (arr1.Length > arr2.Length)
  24. {
  25. for (int i = 0; i < maxLen; i++)
  26. {
  27. if (i < arr2.Length)
  28. {
  29. tempArr[i] = arr2[i];
  30. }
  31. else
  32. {
  33. tempArr[i] = 0;
  34. }
  35. }
  36.  
  37. for (int i = 0; i < sum.Length; i++)
  38. {
  39. if (i < arr1.Length)
  40. {
  41. sum[i] = (arr1[i] + tempArr[i]) % 10;
  42. }
  43. if (i > 0 && arr1[i - 1] + tempArr[i - 1] >= 10)
  44. {
  45. sum[i] += 1;
  46. }
  47. //Console.Write(sum[i] + ", ");
  48. }
  49. }
  50. else
  51. {
  52. for (int i = 0; i < maxLen; i++)
  53. {
  54. if (i < arr1.Length)
  55. {
  56. tempArr[i] = arr1[i];
  57. }
  58. else
  59. {
  60. tempArr[i] = 0;
  61. }
  62. }
  63.  
  64. for (int i = 0; i < sum.Length; i++)
  65. {
  66. if (i < arr2.Length)
  67. {
  68. sum[i] = (arr2[i] + tempArr[i]) % 10;
  69. }
  70. if (i > 0 && arr2[i - 1] + tempArr[i - 1] >= 10)
  71. {
  72. sum[i] += 1;
  73. }
  74. //Console.Write(sum[i] + ", ");
  75. }
  76. }
  77.  
  78. string resultString = "";
  79.  
  80. for (int i = sum.Length - 1; i >= 0; i--)
  81. {
  82. resultString += sum[i];
  83. }
  84.  
  85. BigInteger result = BigInteger.Parse(resultString);
  86.  
  87. return result;
  88. }
  89.  
  90. static void Main(string[] args)
  91. {
  92. int[] arr1 = {9, 1, 1, 1};
  93. int[] arr2 = {9, 2, 3, 9};
  94.  
  95. BigInteger result = addArraysOfDigits(arr1, arr2);
  96. Console.WriteLine(result);
  97. }
  98. }
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement