Jquery convert integer to string and back

These are the logical steps I need to take with jquery:

x - This is a 2-digit number (integer) obtained from input.value ();

If  var x is **not** 33 or 44
    Convert this 2 digit number to string;
    split the string in 2 parts as number;
    Add these 2 values until they reduce to single digit;
    Return var x value as this value;
Else
    Return var x value literally as 33 or 44 whatever is the case;

Thank!

+5
source share
2 answers
if (x != 33 && x != 44) {
    while (x > 9) {
        var parts = ('' + x).split('');
        x = parseInt(parts[0]) + parseInt(parts[1]);
    }
    return x;
} else {
    return x;
}    

It only works if the input really has max 2 digits, as you say, otherwise you will need to add numbers in the loop foron top parts.length. For instance:.

if (x != 33 && x != 44) {
    while (x > 9) {
        var parts = ('' + x).split('');
        for (var x = 0, i = 0; i < parts.length; i++) {
            x += parseInt(parts[i]);
        }
    }
    return x;
} else {
    return x;
}    
+3
source

I would try:

function process (x) {
    if ((x != 33) && (x != 44)) {
        while (x > 9) {
            x = Math.floor (x / 10) + (x % 10);
        }
    }
    return x;
}

I see little reason to convert it to a string when you can use arithmetic operations.

+1
source

All Articles