java - 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;
}
解决方案
作为网友的建议,我删除包语句后它通过了,这真的很奇怪。
推荐阅读
- java - 如何使用 Selenium WebDriver 或 JS 等待 iframe 内容加载?
- snakemake - 使用 Snakemake 时如何修复“文件名太长”错误
- python - NameError 即使变量被初始化
- python - 使用 Beautiful Soup 抓取具有 URL 的弹出窗口(以及其他错误)
- java - 谁能解释为什么 int x=1_000_000 是有效的并打印 1000000 而不是抛出错误?
- nginx - 为 Nginx Ingress 中的特定位置设置 limit_req
- ruby-on-rails - 在部署到 EB 时升级 Ruby 版本
- joomla3.0 - 几个网站上的 Joomla SEF URL 问题
- java - 将多个 Apache Beam 管道打包到一个 jar 文件中
- python - python中的http代理,我应该何时以及如何关闭连接?