首页 > 解决方案 > Why does my algorithm to output every digit of a sum fail In PTA?

问题描述

I wrote some code to solve the problem below. I have trid some test cases and they all pass, but when I submit my answer for automatic marking, the result is a fail. I have no idea where is the problem.

Here is the problem and the corresponding link:

1005 Spell It Right (20 分)
Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English.

Input Specification:
Each input file contains one test case. Each case occupies one line which contains an N (≤10^100​​).

Output Specification:
For each test case, output in one line the digits of the sum in English words. There must be one space between two consecutive words, but no extra space at the end of a line.

Sample Input:

12345

Sample Output:

one five

Below is my codes(It needs to replace the class name to be Main before submit to system):

package com.maxim.advance;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

public static void main(String args[]) {
    Scanner scanner = new Scanner(System.in);
    String input = scanner.nextLine();
    scanner.close();
    int length = input.length();
    int sum = 0;
    for (int index = 0; index < length; index++) {
        sum += input.charAt(index) - '0';
    }
    // Consider sum == 0 case;
    if (sum == 0) {
        System.out.print("zero");
    }

    String[] names = new String[] {
            "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
    };


    List<String> outputs = new ArrayList<String> (100);
    while (sum > 0) {
        outputs.add(names[sum % 10]);
        sum = sum / 10;
    }


    int size = outputs.size();

    for (int i = size - 1; i >= 0; i--) {
        if (i > 0) {
            System.out.print(outputs.get(i) + " ");
        } else {
            System.out.print(outputs.get(i));
        }

    }
}
}

The C++ codes below are correct and pass always

#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
long int tmp=0;
for(int i=0;i<s.size();i++){
    tmp+=(s[i]-'0');
}
string match[10]={"zero","one","two","three","four","five","six","seven","eight","nine"};
vector<string> v;
long int sum=tmp;
while(sum){
    v.push_back(match[sum%10]);
    sum/=10;
}

reverse(v.begin(),v.end());
if(tmp==0)// 
cout<<"zero";
else
for(int i=0;i<v.size();i++){
    if(i==0)
    cout<<v[i];
    else
    cout<<" "<<v[i];
}
return 0;
}

标签: javaalgorithm

解决方案


作为网友的建议,我删除包语句后它通过了,这真的很奇怪。


推荐阅读