plduhoux
2/22/2018 - 5:53 PM

swapNeighbouringDigits

int swapNeighbouringDigits(int n) {
    //Swap digits two by two from left and right
    /*String nb = ""+n;
    int res = 0;
    for (int i = 0; i < nb.length() / 2; i++) {
        res += Math.pow(10, nb.length() - i - 1) * (nb.charAt(nb.length() -i-1) - 48);
        res += Math.pow(10, i) * (nb.charAt(i) - 48);
    }
    return res;*/
    int res = 0; 
    int p = 0;
    while (n != 0) {
        int d1 = n % 10;
        n /= 10;
        int d2 = n % 10;
        n /= 10;
        res += Math.pow(10, p + 1) * d1 + Math.pow(10, p) * d2;
        p += 2;
    }
    return res;
}