Created
February 2, 2017 18:27
-
-
Save ddsilva/356f06a0417fcbdedc16a9660796504b to your computer and use it in GitHub Desktop.
Numbers in the text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!-- | |
| Dada uma seqüência aleatória consistindo de números, letras, símbolos, você precisa somar os números na seqüência de caracteres. | |
| Nota: | |
| Inteiros consecutivos devem ser tratados como um único número. Por exemplo, 2015 deve ser tratado como um único número 2015, NÃO quatro números | |
| Todos os números devem ser considerados como número inteiro positivo. Por exemplo, 11-14 deve ser tratado como dois números 11 e 14. Mesmo que 3,14, deve ser tratado como dois números 3 e 14 | |
| Se nenhum número foi dado na string, ele deve retornar 0 | |
| Exemplo: | |
| "Em 2015, eu quero saber quanto custa o iPhone 6 +?" -> 2015, 6 => 2021 | |
| --> | |
| <html> | |
| <head> | |
| <style> | |
| #container{ | |
| font-family:monospace; | |
| font-weight:bold; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div id="container"></div> | |
| <script> | |
| function print(text) { | |
| document.getElementById('container').innerText += text + '\n'; | |
| } | |
| function assert(text, test) { | |
| print(text + ': ' + test); | |
| } | |
| function getNumbers(text) { | |
| return text.match(/[\d]+/g); | |
| } | |
| function sumNumbers(text) { | |
| if ((typeof text) === 'number') { | |
| return Math.floor(text); | |
| } | |
| if ((typeof text) !== 'string') { | |
| return 0; | |
| } | |
| var numbers = getNumbers(text); | |
| if(!numbers) { | |
| return 0; | |
| } | |
| return numbers.reduce(function(current, next) { | |
| return parseInt(current) + parseInt(next); | |
| }, 0); | |
| } | |
| assert('1', sumNumbers('1') === 1); | |
| assert('{}', sumNumbers({}) === 0); | |
| assert('15/10/1988', sumNumbers('15/10/1988') === 2013); | |
| assert('Msg do enunciado', | |
| sumNumbers('Em 2015, eu quero saber quanto custa o iPhone 6 +?') === 2021); | |
| assert('teste', sumNumbers('teste') === 0); | |
| assert('10-2.4 10', sumNumbers('10-2.4 10') === 26); | |
| assert('10', sumNumbers(10) === 10); | |
| assert('10,5', sumNumbers(10.5) === 10); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment