Check number divisibility with regular expressions

前端 未结 6 2163
我寻月下人不归
我寻月下人不归 2020-12-05 18:39

Given a decimal number N as a string of digits, how do I check if it\'s divisible by M using regular expressions only, without con

6条回答
  •  执笔经年
    2020-12-05 19:36

    Here is a generic straight forward recursive brute force long division. It's not optimized and definitely not elegant lol. It's in JavaScript (below is a test html page with the code):

    
    
    
    
    
    
    
    
    
    
    
    

    The idea is for M = 7 (example):

    while(numStr.length > 1) {
        numStr = numStr.replace(/^(14|21|35|42|56|63)/, "");
        numStr = numStr.replace(/^(15|22|36|43|50|64)/, "1");
        numStr = numStr.replace(/^(16|23|30|44|51|65)/, "2");
        numStr = numStr.replace(/^(10|24|31|45|52|66)/, "3");
        numStr = numStr.replace(/^(11|25|32|46|53|60)/, "4");
        numStr = numStr.replace(/^(12|26|33|40|54|61)/, "5");
        numStr = numStr.replace(/^(13|20|34|41|55|62)/, "6");
    }
    

提交回复
热议问题