Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda