202 - Repeating Decimals

欢迎folk或者star我的repo:https://github.com/guopeiming/algorithm-training,每天更新一道oj入门紫皮书上的题目或者oj、LeetCode,持续更新中

#include <stdio.h> #include <string.h> using namespace std; int isExist(int* list, int size, int val); int main(){ int m, n, divided[5000], count, idx, flag; char decimal[5000]; while(scanf("%d%d", &m, &n) != EOF){ count = 0, idx = -1; memset((void *)divided, '\0', 500); memset(decimal, '\0', 500); printf("%d/%d = %d.", m, n, m / n); m = m % n; while(true){ m = m * 10; idx = isExist(divided, count, m); if(idx != -1){ break; } divided[count] = m; decimal[count] = (m / n) + '0'; m = m % n; count++; } for(int i = 0; i < idx; ++i){ if(i >= 50){ break; } printf("%c", decimal[i]); } printf("("); for(int i = idx; i < count; ++i){ if(i >= 50){ printf("..."); break; } printf("%c", decimal[i]); } printf(")\n"); printf(" %d = number of digits in repeating cycle\n\n", count - idx); } } int isExist(int* list, int size, int val){ for(int i = 0; i < size; ++i){ if(list[i] == val){ return i; } } return -1; } // Sample Input // 76 25 // 5 43 // 1 397 // Sample Output // 76/25 = 3.04(0) // 1 = number of digits in repeating cycle // 5/43 = 0.(116279069767441860465) // 21 = number of digits in repeating cycle // 1/397 = 0.(00251889168765743073047858942065491183879093198992...) // 99 = number of digits in repeating cycle //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=830&page=show_problem&problem=138 //还是要注意整除与取余在数字运算中的重要作用 //代码能力!!!

 

posted @ 2019-06-04 21:41  回溯法  阅读(142)  评论(0编辑  收藏  举报