给一个数字的每一位加一的程序

  • 本文关键字:一位 程序 数字 一个 c
  • 更新时间 :
  • 英文 :


作为竞争性编程的新手,我正在解决这个练习问题。目标是编写一个程序来显示数字比输入数字的相应数字大1的数字。因此,如果输入的数字是12345,那么输出的数字应该是23456。我已经想好了如何将每个数字分开并相加,但我无法在下面的程序中接受数量的测试用例

问题如下

输入

输入的第一行将包含一个数字N=测试用例的数量。接下来的N行将包含数字N作为测试情况,其中1<n<99999.

输出

对于每个输入案例,在n的每个数字上加一,然后打印新的数字。

作为竞争性编程的初学者,如果你能给出一些优化代码的技巧,那将是很有帮助的。

这是我写的代码。

#include<stdio.h>
void main()
{
int n, t, sum = 0;
scanf("%d", &t);
int a[t];
for (int j = 0; j < t; j++)
{
for (int i = 0; i < t; i++)
{
scanf("%d", &n);
a[i] = n;
if (t == 1) {
if (i == 0) {
a[i] = (a[i] + 1) * 1;
}
}
else if (t == 2) {
if (i == 0) {
a[i] = (a[i] + 1) * 10;
}
else if (i == 1) {
a[i] = (a[i] + 1) * 1;
}
}
else if (t == 3) {
if (i == 0) {
a[i] = (a[i] + 1) * 100;
}
else if (i == 1) {
a[i] = (a[i] + 1) * 10;
}
else if (i == 2) {
a[i] = (a[i] + 1) * 1;
}
}
else if (t == 4) {
if (i == 0) {
a[i] = (a[i] + 1) * 1000;
}
else if (i == 1) {
a[i] = (a[i] + 1) * 100;
}
else if (i == 2) {
a[i] = (a[i] + 1) * 10;
}
else if (i == 3) {
a[i] = (a[i] + 1) * 1;
}
}
else if (t == 5) {
if (i == 0) {
a[i] = (a[i] + 1) * 10000;
}
else if (i == 1) {
a[i] = (a[i] + 1) * 1000;
}
else if (i == 2) {
a[i] = (a[i] + 1) * 100;
}
else if (i == 3) {
a[i] = (a[i] + 1) * 10;
}
else if (i == 4) {
a[i] = (a[i] + 1) * 1;
}
}
else if (t == 6) {
if (i == 0) {
a[i] = (a[i] + 1) * 100000;
}
else if (i == 1) {
a[i] = (a[i] + 1) * 10000;
}
else if (i == 2) {
a[i] = (a[i] + 1) * 1000;
}
else if (i == 3) {
a[i] = (a[i] + 1) * 100;
}
else if (i == 4) {
a[i] = (a[i] + 1) * 10;
}
else if (i == 4) {
a[i] = (a[i] + 1) * 1;
}
}
}
}
for (int i = 0; i < t; i++)
{
sum = sum + a[i];
}
printf("%dn", sum);
}

我从一开始就重新编写了代码,并为您制定了一个解决方案:

#include <stdio.h>
int main(void)
{
int num, sum, remainder, check; // check used as a boolean expression
sum = check = 0;
printf("Enter the sequence: ");
scanf("%d", &num);
while (num > 0)
{
remainder = num % 10; // each time num is reduced
if (remainder != 9)
{
if (check == 0)
sum = (10 * sum) + (remainder + 1);
else
{
sum = (10 * sum) + (remainder + 2);
check = 0;
}
}
else
{
sum = (10 * sum) + 0;
check = 1;
}
num /= 10; // will divide and execute in each iteration until it's true
}
num = sum; // final number will be equal to the sum
sum = 0;
// Summing up the results
while (num > 0)
{
remainder = num % 10;
sum = (10 * sum) + remainder;
num /= 10;
}
printf("Result: %dn", sum);
return 0;
}

测试输出

Enter the sequence: 23456
Result: 34567

这只是关于总和&余数希望它能帮助你更好地理解。

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int num,i=1,j;
Scanner scan=new Scanner(System.in);
int numo=scan.nextInt();num=numo;
for(;numo>0;numo=numo/10,i=i*10)
{
num=num+i;
if(numo%10==9)  
num=num-i*10;  
} 
System.out.println(num);
}
}

以下解决方案使用基本余数和反向方法:

int addOne(int n)
{
int rem, ans=0, p=1 ;
while(n>0)
{
rem = n%10;
(rem == 9)?rem = 0:rem+=1;
ans+=p*rem;
p*=10;n/=10;
}
return ans;
}
int main() {

int n;
cin>>n;
cout<<addOne(n);
return 0;
}

最新更新