这几个题目的难度为递增。
1.给定一个整数,输出该整数是一个几位数字,数字可能是负数,0或者正数.
例如 12345678输出8; 0输出1; -123456789输出9。
int main()
{
long long x;
scanf("%lld",&x);
int count = 0;//统计位数
do
{
count++;
x /= 10;//丢弃个位数字
}while (x != 0);
printf("%d\n",count);
return 0;
}
用丢弃个位的方法,是数字常用的处理方式。
—————————————————————————
2.给定一个整数,逆序输出每一位,数字可能是负数,0或者正数.
例如 123456789,输出9 8 7 6 5 4 3 2 1
例如-123456789,输出 -9 8 7 6 5 4 3 2 1
int main()
{
long long x;
scanf("%lld",&x);
if (x < 0)
{
printf("-");
x = -x;//char :-128~127,bug
}
if (x == 0)
{
printf("0\n");
return 0;
}
while (x != 0)
{
printf("%d ",x%10);//得到个位数字
x /= 10;//丢弃个位数字
}
return 0;
}
得到个位数字输出,然后再丢弃。
——————————————————————————
3.给定一个整数,顺序输出该整数每一位数字,数字可能是负数,0或者正数.
例如 123456789,输出1,2,3,4,5,6,7,8,9
例如-123456789,输出 -1,2,3,4,5,6,7,8,9
int main()
{
long long n;
scanf("%lld",&n);
if (n == 0)
{
printf("0\n");
return 0;
}
else if (n < 0)
{
printf("-");
n = -n;
}
int count = 0;//统计位数
long long m = n;
while (m != 0)//得到m的位数
{
count++;
m /= 10;//丢弃个位
}
int power = pow(10,count-1);//如果n==123456,power=100000
while (n != 0)
{
printf("%d,",n/power);//输出最高位
n %= power;//丢弃最高位
power /= 10;
}
return 0;
}