Separating digits in decimal representation of integer

后端 未结 3 348
我在风中等你
我在风中等你 2021-01-17 05:10

I want to take user input entered as an integer, for example (45697), and store the first two digits in an array, vector, or something else such as ( 4 5

3条回答
  •  鱼传尺愫
    2021-01-17 05:45

    There is nothing wrong with a string-based approach, but here is a mathematical solution to getting all of the digits:

    >> x = 45697
    x =
    
           45697
    
    >> numDigits = floor(log10(x)+1)
    numDigits =
    
         5
    
    >> tens = 10.^(1:numDigits);
    >> digitArray = fliplr(floor(mod(x,tens)./(tens/10)))
    digitArray =
    
         4     5     6     9     7
    

    The crux of this method is to use mod to chip off the high digits one at a time, shifting the new first digit down to the ones place, and finally truncating down to the get the integer value at that position.

    In the case of the OP, the required values are digitArray(1:2).

提交回复
热议问题