Tuesday, December 8, 2009

Integer to String

 String intToStr( int num ){
    int i = 0;
    boolean isNeg = false;
    /* Buffer big enough for largest int and - sign */
    char[] temp = new char[ MAX_DIGITS + 1 ];

    /* Check to see if the number is negative */
    if( num < 0 ){
        num *= -1;
        isNeg = true;
    }

    /* Fill buffer with digit characters in reverse order */
    do {
        temp[i++] = (char)((num % 10) + '0');
        num /= 10;
    } while( num != 0 );

    StringBuffer b = new StringBuffer();
    if( isNeg )
        b.append( '-' );

    while( i > 0 ){
        b.append( temp[--i] );
    }

    return b.toString();
}

No comments:

Post a Comment