由于这里的其他答案都没有在严格意义上符合“无内置”的要求,因此我将以下扩展提交给Python,以供OP使用:/* rem_odd.c */
#include
#include
static PyObject *
rem_odd(PyObject *self, PyObject *args)
{
int digit, ix, n, num, result;
int digits[20]; /* handles up to 2^64 (20 digits) */
if (!PyArg_ParseTuple(args, "i", &num))
return NULL;
n = num;
ix = 0;
while (n > 0) {
digit = n % 10;
n /= 10;
if (digit % 2 == 0)
digits[ix++] = digit;
}
result = 0;
while (ix-- >= 0) {
result += (int)(pow(10., ix)) * digits[ix];
}
return Py_BuildValue("i", result);
}
static PyMethodDef RemOddMethods[] = {
{"rem_odd", rem_odd, METH_VARARGS,
"Remove odd digits from an integer and return another integer."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
initrem_odd(void)
{
(void) Py_InitModule("rem_odd", RemOddMethods);
}
然后使用distutils:
^{pr2}$
示例用法(在运行setup.py build和setup.py install之后):
^{3}$