整数转字符串

//支持负数转字符串

std::string num_to_str(const int value)
{
    std::string str;
    std::string falg;
    int temp_value = value;
    int falg_pos = temp_value >> 31;//判断符号位

    if (falg_pos < 0) {
        falg += "-";
        temp_value = ((~temp_value) + 1);//负变正,正变负
    }

    while (temp_value >0){
        str += temp_value % 10 + '0';
        temp_value /= 10;
    }
    
    //逆序
    size_t right_idex = str.size() - 1;
    size_t left_index = 0;
    while (left_index <right_idex){
        char temp = str[left_index];
        str[left_index++] = str[right_idex];
        str[right_idex--] = temp;
    }

    falg += str;
    return std::move(falg);
}

猜你喜欢

转载自blog.csdn.net/qq_53332653/article/details/114656042
今日推荐