# 【九度】题目1491：求1和2的个数

833人阅读 评论(0)

10
11

3
5

2013年王道论坛研究生机试练习赛（三）
【解题思路】

Java AC

import java.util.Scanner;

public class Main {
/*
* 1491
*/
private static int mod = 20123;
private static char array[];
private static int len;
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String input = scanner.next();
array = input.toCharArray();
len = array.length;
System.out.println(modValue(calCount(1) + calCount(2)));
}
}

private static int calCount(int num) {
int k = len - 1;
int factor = 1;
int count = 0;
while (k >= 0) {
int lowNum = 0;
int currNum = 0;
int highNum = 0;
for (int i = 0; i < k; i++) {
highNum = modValue(modValue(highNum * 10) + (array[i] - '0'));
}
for (int i = k+1; i < len; i++) {
lowNum = modValue(modValue(lowNum * 10) + array[i] - '0');
}
currNum = array[k] - '0';
if (currNum < num){
count = modValue(count + highNum * factor);
}else if (currNum == num) {
count = modValue(count + highNum * factor + lowNum + 1);
}else if (currNum > num) {
count = modValue(count + (highNum + 1) * factor);
}

factor = modValue(factor * 10);
k--;
}
return count;
}

private static int modValue(int n) {
return n % mod;
}
}

/**************************************************************
Problem: 1491
User: wzqwsrf
Language: Java
Result: Accepted
Time:130 ms
Memory:18248 kb
****************************************************************/

C++ AC

#include <stdio.h>
#include <string.h>

const int mod = 20123;
int len;
int i;
char array[1000];
int modValue(int n){
return n % mod;
}

int calCount(int num) {
int k = len - 1;
int factor = 1;
int count = 0;
while (k >= 0) {
int lowNum = 0;
int currNum = 0;
int highNum = 0;
for (i = 0; i < k; i++) {
highNum = modValue(modValue(highNum * 10) + (array[i] - '0'));
}
for (i = k+1; i < len; i++) {
lowNum = modValue(modValue(lowNum * 10) + array[i] - '0');
}
currNum = array[k] - '0';
if (currNum < num){
count = modValue(count + highNum * factor);
}else if (currNum == num) {
count = modValue(count + highNum * factor + lowNum + 1);
}else if (currNum > num) {
count = modValue(count + (highNum + 1) * factor);
}

factor = modValue(factor * 10);
k--;
}
return count;
}

int main(){

while(scanf("%s",&array) != EOF){
len = strlen(array);
printf("%d\n",modValue(calCount(1) + calCount(2)));
}
return 0;
}
/**************************************************************
Problem: 1491
User: wzqwsrf
Language: C++
Result: Accepted
Time:10 ms
Memory:1020 kb
****************************************************************/
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：254438次
• 积分：5140
• 等级：
• 排名：第5353名
• 原创：263篇
• 转载：16篇
• 译文：0篇
• 评论：47条
github
博客专栏
 九度OJ解题报告 文章：102篇 阅读：78354
 LeetCode解题报告 文章：121篇 阅读：114748
最新评论