fork download
  1. using static System.Console;
  2. using System;
  3. using System.Text;
  4.  
  5. public static class Boleto {
  6. public static string Modulo11LinhaDigitavel(string valor, int digitoBase = 9, bool resto = false) {
  7. var linha = new StringBuilder(valor.Length);
  8. for (var i = 0; i < valor.Length; i++) {
  9. if ("0123456789".IndexOf(valor[i]) >= 0) linha.Append(valor.Substring(i, 1));
  10. }
  11. var linhaOrdenada = linha.ToString();
  12. linhaOrdenada = linhaOrdenada.Substring(0, 4) +
  13. linhaOrdenada.Substring(32, 15) +
  14. linhaOrdenada.Substring(4, 5) +
  15. linhaOrdenada.Substring(10, 10) +
  16. linhaOrdenada.Substring(21, 10);
  17. linhaOrdenada = linhaOrdenada.Substring(0, 4) + linhaOrdenada.Substring(5, 39);
  18. var soma = 0;
  19. var peso = 2;
  20. for (var i = linhaOrdenada.Length - 1; i >= 0; i--) {
  21. soma += Convert.ToInt32(linhaOrdenada.Substring(i, 1)) * peso;
  22. if (peso < digitoBase) peso++;
  23. else peso = 2;
  24. }
  25. var retorno = "";
  26. if (resto) {
  27. retorno = (soma % 11).ToString();
  28. } else {
  29. var digito = 11 - (soma % 11);
  30. if (digito > 9) {
  31. digito = 0;
  32. }
  33. retorno = digito.ToString();
  34. }
  35. if (retorno == "0") return "1";
  36. return retorno;
  37. }
  38.  
  39. // Uma vez funcionado, teria que retornar 5, que é o DV da linha digitável abaixo em questão
  40. public static void Main(string[] args) {
  41. WriteLine(Modulo11LinhaDigitavel("10490.05539 03698.700006 00091.449587 5 55490000028531"));
  42. WriteLine(Modulo11LinhaDigitavel("34198.85912 01354.522771 90199.970006 7 55100000500000"));
  43. WriteLine(Modulo11LinhaDigitavel("39992.84841 90000.001702 12459.064122 1 48970000041452"));
  44. WriteLine(Modulo11LinhaDigitavel("03399.54083 26100.000129 04389.301021 8 57750000008990"));
  45. WriteLine(Modulo11LinhaDigitavel("23792.02803 60002.775660 63002.490009 3 53270000121000"));
  46. WriteLine(Modulo11LinhaDigitavel("34191.75009 37645.262934 80706.420009 9 57680000521600"));
  47. WriteLine(Modulo11LinhaDigitavel("10490.05539 03698.700006 00350.368361 4 67750000010156"));
  48. }
  49. }
  50.  
  51. //https://pt.stackoverflow.com/q/125480/101
Success #stdin #stdout 0.02s 16392KB
stdin
Standard input is empty
stdout
5
7
1
8
3
9
4