Monotone Increasing Digits

LeetCode Q 738 - Monotone Increasing Digits

Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.
(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.)

Example 1: Input: N = 10 ; Output: 9

Example 2: Input: N = 1234 ; Output: 1234

Example 3: Input: N = 332 ; Output: 299

Note: N is an integer in the range [0, 10^9].

Solution

input  :  332, 
step 1 :  2, 3, 3    // record each digit in the array
step 2 :  2, 2, 2,  pos = 2  // whenever we find a digit larger than its left digit, we decrease this large digit by 1 and record its position.
step 3 :  9, 9, 2    // from left up to the pos before the recorded pos, we set digits in those positions to 9.
step 4 :  299    // transform the arr to number

Code:

public int monotoneIncreasingDigits(int N) {
	
	int[] digits = new int[10];

	// get each digit in N, in small index we store high weight digit
	int index = 0;
	while (N != 0) {
		digits[index++] = N % 10;
		N /= 10;
	}

	int pos = 0; // at pos, we minus that digit by one 
				// at pos - 1,... we need to set the digits to 9

	for (int i = 1; i < index; i++) {
		if (digits[i] > digits[i - 1]) {
			digits[i]--; pos = i;
		}
	}

	for (int i = 0; i < pos; i++) {
		digits[i] = 9;
	}

	int res = 0;
	for (int i = index - 1; i >= 0; i--) 
		res += res * 10 + digits[i];

	return res;
}

   Reprint policy


《Monotone Increasing Digits》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
 Previous
Reorganize String Reorganize String
LeetCode Q 767 - Reorganize StringGiven a string S, check if the letters can be rearranged so that two characters that a
2019-05-31 Tong Shi
Next 
Partition Labels Partition Labels
LeetCode Q 763 - Partition LabelsA string S of lowercase letters is given. We want to partition this string into as many
2019-05-31 Tong Shi
  TOC