Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
HackerRank Plus Minus problem: Typescript

I am trying to solve the Plus Minus problem in HackerRank using Typescript. I am getting NaN as result in first two print statements, however, the last one is working. This is my solution:

function plusMinus(arr: number[]): void {
    // Write your code here
    
    let pos: number, neg: number, zero: number = 0; 
    
    for (let i=0; i< arr.length; i++){
        if(arr[i]>0){
            pos+=1; 
        }
        else if(arr[i]<0){
            neg+=1;
        }
        else{
            zero+=1; 
        }
    }
    let len: number = arr.length;
    let posRatio = (pos/len).toFixed(6);
    let negRatio = (neg/len).toFixed(6);
    let zeroRatio = (zero/len).toFixed(6); 
    
    console.log(posRatio);
    console.log(negRatio);
    console.log(zeroRatio);
    
}

Here is the output:

Compiler Message
Wrong Answer

Input (stdout)
6
-4 3 -9 0 4 1

Your Output (stdout)
NaN
NaN
0.166667

Expected Output

0.500000
0.333333
0.166667

Can anyone help me out to understand what the problem might have been?

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

let pos: number, neg: number, zero: number = 0; 

You only defined a default value for zero in the above line. In JS (or TS), the default value of any variable is undefined unless you explicitly set one.

undefined + 1 is NaN.

console.log(undefined + 1)

Further reading

about 4 years ago · Santiago Gelvez Relatório

0

Issue is in your value initialization.

let pos: number, neg: number, zero: number = 0; 

If you would log this you will get

pos=undefined
neg=undefined
zero=0

and now if you try to add number with undefined it will give you NaN

Initialize pos, neg and zero to 0 properly.

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda