HDU-1212 Big Number JAVA又出毛病了

來源:互聯網
上載者:User

http://acm.hdu.edu.cn/showproblem.php?pid=1212

  

  不料JAVA又出問題了,Scanner 類竟然識別不出來,我不知道哪裡出了問題,這題是求一個大數對一個相對較小的數的取餘運算。剛開始的想法很傻很天真啊,直接計算出被除數的位元,再取相應的位元取餘。這可是不知道錯哪去了,這是對 10^K 次方的數的取餘操作,放在這裡顯然是不合適的,如果硬要這麼做的話,那麼前提就是這個數必須是以MOD為進位的數。該題是這樣處理的,首先判斷是否滿了6位,如果大於6位元字,那麼就可以利用較高一位的單位量取餘值等於低一位的取餘值乘以十再取餘。

  代碼如下:

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
using namespace std;

char num[1005];

inline int _pow( int N )
{
int res = 1;
for( int i = 0; i < N; ++i )
res *= 10;
return res;
}

int main()
{
int MOD, res, base;
while( scanf( "%s %d", num, &MOD ) == 2 )
{
res = 0;
base = 1000000 % MOD;
int len = strlen( num );
for( int i = len - 1, j = 0; i >= 0 && j < 6; --i, ++j )
{
res += ( num[i] - '0' ) * _pow( j );
}
if( len > 6 )
{
for( int i = len - 7; i >= 0; --i )
{
res += ( base * ( num[i] - '0' ) ) % MOD;
base = ( base * 10 ) % MOD;
}
}
printf( "%d\n", res % MOD );
}
return 0;
}

 

  這是網上叫我慚愧的代碼,思路簡潔,代碼精簡:

  

#include<stdio.h>
#include<string.h>
int main()
{
int n,sum,i,k;
char s[1001];
while(scanf("%s%d",s,&n)!=EOF)
{
k=strlen(s);
sum=0;
for(i=0;i<k;i++)
{
sum=sum*10+s[i]-'0';
sum=sum%n;
}
printf("%d\n",sum);
}
return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.