Advertisement

PAT-BASIC1057——数零壹

阅读量:

我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC

原题链接:https://pintia.cn/problem-sets/994805260223102976/problems/994805270914383872

题目描述:

知识点:进制转换

思路:先根据题目规则求和,再进行进制转换求0和1的个数

本题有一个坑点:

本题中,如果字符串中没有任何一个英文字母,我们应该输出什么呢?显然这时整数N应该为0,为什么说应该为0呢?因为题目并没有明确说字符串中没有任何一个英文字母时N的值应该是多少。按照本题的测试程序,测试点2就是字符串中没有任何一个英文字母的情况,这个时候我们应该输出"0 0",即把0和1的个数均看作是0。

本题十进制转二进制求0和1个数的正确写法:

复制代码
 int count0 = 0;

    
 int count1 = 0;
    
 while(N > 0) {
    
     if(N % 2 == 0) {
    
     count0++;
    
 	} else {
    
 		count1++;
    
 	}
    
 	N /= 2;
    
 }
    
    
    
    

一开始我的写法是这样的:

复制代码
 int count0 = 0;

    
 int count1 = 0;
    
 while(N >= 2) {
    
 	if(N % 2 == 0) {
    
 		count0++;
    
 	} else {
    
 		count1++;
    
 	}
    
 	N /= 2;
    
 }
    
 if(N == 1) {
    
     count1++;
    
 } else if(N == 0) {
    
     count0++;
    
 }
    
    
    
    

我的这个写法和第一种写法的差别仅在于N为0时,第一种写法输出的0和1的个数均是0,而我的写法输出的0的个数会是1,1的个数是1。

由于测试点2规定了字符串中没有任何一个英文字母时,输出0和1的个数均是0。而我的程序里又定义了N的初值是0,所以字符串中没有任何一个英文字母时N值会是0,如果采用我的第二种写法,会输出"1 0",无法通过测试点2。

时间复杂度是O(n),其中n为输入字符串的长度。空间复杂度是O(1)。

C++代码:

复制代码
 #include<iostream>

    
 #include<string>
    
  
    
 using namespace std;
    
  
    
 int main() {
    
 	string input;
    
  
    
 	getline(cin, input);
    
  
    
 	long N = 0;
    
 	for(int i = 0; i < input.length(); i++) {
    
 		if(input[i] >= 'a' && input[i] <= 'z') {
    
 			N += (input[i] - 'a') + 1;
    
 		} else if(input[i] >= 'A' && input[i] <= 'Z') {
    
 			N += (input[i] - 'A') + 1;
    
 		}
    
 	}
    
  
    
 	int count0 = 0;
    
 	int count1 = 0;
    
 	while(N > 0) {
    
 		if(N % 2 == 0) {
    
 			count0++;
    
 		} else {
    
 			count1++;
    
 		}
    
 		N /= 2;
    
 	}
    
 	cout << count0 << " " << count1 << endl;
    
  
    
 	return 0;
    
 }
    
    
    
    

C++解题报告:

全部评论 (0)

还没有任何评论哟~